#include <wx/wxprec.h>

#ifdef __BORLANDC__
	#pragma hdrstop
#endif

#ifndef WX_PRECOMP
	#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/file.h>
#include <wx/filename.h>
#include <wx/wfstream.h>
#include <wx/datstrm.h>
#include <wx/textfile.h>
#include <wx/printdlg.h>
#include <wx/artprov.h>
#include "myapp.h"
#include "kakeibo.h"

#include "kakeibomeister.xpm"

DECLARE_APP(MyApp);

BEGIN_EVENT_TABLE(MyFrame, wxFrame)
//---file menu
	EVT_MENU(kakeibo_new,MyFrame::fileMenu_New_clicked)
	EVT_MENU(kakeibo_open,MyFrame::fileMenu_Open_clicked)
	EVT_MENU(kakeibo_save,MyFrame::fileMenu_Save_clicked)
	EVT_MENU(kakeibo_saveas,MyFrame::fileMenu_Save_clicked)
	EVT_MENU(kakeibo_close,MyFrame::fileMenu_Close_clicked)
	EVT_MENU_RANGE(kakeibo_recent01,kakeibo_recent05,MyFrame::fileMenu_Recent_clicked)
	EVT_MENU(kakeibo_exit,MyFrame::fileMenu_Exit_clicked)
	EVT_MENU(kakeibo_setprinter,MyFrame::fileMenu_SetPrinter_clicked)
//---edit menu
	EVT_MENU(kakeibo_adddetail,MyFrame::km_AddDetail_clicked)
	EVT_MENU(kakeibo_moddetail,MyFrame::km_ModDetail_clicked)
	EVT_MENU(kakeibo_cut,MyFrame::editMenu_Cut_clicked)
	EVT_MENU(kakeibo_copy,MyFrame::editMenu_Copy_clicked)
	EVT_MENU(kakeibo_paste,MyFrame::editMenu_Paste_clicked)
	EVT_MENU(kakeibo_deldetail,MyFrame::km_DelDetail_clicked)
	EVT_MENU(kakeibo_addfav,MyFrame::editMenu_AddFavorite_clicked)
	EVT_MENU(kakeibo_delfav,MyFrame::editMenu_DelFavorite_clicked)
	EVT_MENU_RANGE(kakeibo_fav01,kakeibo_fav20,MyFrame::editMenu_GoFavorite_clicked)
//---view menu
	EVT_MENU(kakeibo_viewday,MyFrame::viewMenu_Tabs_clicked)
	EVT_MENU(kakeibo_viewweek,MyFrame::viewMenu_Tabs_clicked)
	EVT_MENU(kakeibo_viewmonth,MyFrame::viewMenu_Tabs_clicked)
	EVT_MENU(kakeibo_viewsearch,MyFrame::viewMenu_Tabs_clicked)
	EVT_MENU(kakeibo_viewreport,MyFrame::viewMenu_Tabs_clicked)
//---tool menu
	EVT_MENU(kakeibo_setgeneral,MyFrame::toolMenu_SetGeneral_clicked)
	EVT_MENU(kakeibo_setperiodicaltran,MyFrame::toolMenu_SetPeriodical_clicked)
	EVT_MENU(kakeibo_setexpense,MyFrame::toolMenu_SetExpense_clicked)
	EVT_MENU(kakeibo_setaccount,MyFrame::toolMenu_SetAccount_clicked)
	//EVT_MENU(kakeibo_callreport,MyFrame::toolMenu_Report_clicked)
	EVT_MENU(kakeibo_import,MyFrame::toolMenu_Import_clicked)
	EVT_MENU(kakeibo_calllog,MyFrame::toolMenu_Log_clicked)
	EVT_MENU(kakeibo_dellog,MyFrame::toolMenu_DelLog_clicked)
//---help menu
	EVT_MENU(kakeibo_contents,MyFrame::helpMenu_Contents_clicked)
	EVT_MENU(kakeibo_about,MyFrame::helpMenu_About_clicked)
//---tool bar
	EVT_TOOL(kakeibo_open,MyFrame::fileMenu_Open_clicked)
	EVT_TOOL(kakeibo_save,MyFrame::fileMenu_Save_clicked)
	EVT_TOOL(kakeibo_close,MyFrame::fileMenu_Close_clicked)
	EVT_TOOL(kakeibo_adddetail,MyFrame::km_AddDetail_clicked)
//---other control event
	EVT_BUTTON(kakeibo_returntoday,MyFrame::km_ReturnToday_clicked)
	EVT_BUTTON(kakeibo_adddetail,MyFrame::km_AddDetail_clicked)
	EVT_BUTTON(kakeibo_moddetail,MyFrame::km_ModDetail_clicked)
	EVT_BUTTON(kakeibo_deldetail,MyFrame::km_DelDetail_clicked)
	EVT_SPINCTRL(kakeibo_calyear,MyFrame::km_CalenYM_spined)
	EVT_SPINCTRL(kakeibo_calmonth,MyFrame::km_CalenYM_spined)
	EVT_CALENDAR_SEL_CHANGED(kakeibo_calendar,MyFrame::km_Calender_changed)
	EVT_LIST_ITEM_SELECTED(kakeibo_daydetail,MyFrame::km_DayDetail_selected)
	EVT_LIST_ITEM_DESELECTED(kakeibo_daydetail,MyFrame::km_DayDetail_deselected)
	EVT_LIST_ITEM_ACTIVATED(kakeibo_daydetail,MyFrame::km_DayDetail_activated)
	EVT_NOTEBOOK_PAGE_CHANGED(kakeibo_main2,MyFrame::mainPanel2_changed)
	EVT_CHOICE(kakeibo_toolhandling,MyFrame::km_tool_Handling_selected)
	EVT_CLOSE(MyFrame::MyFrame_close)
	EVT_LISTBOX_DCLICK(kakeibo_stockbudget,MyFrame::km_StackPeriod_dblclicked)
	EVT_CHOICE(kakeibo_serio,MyFrame::km_SerIO_changed)
	EVT_COMBOBOX(kakeibo_serexpense,MyFrame::km_SerUseExpense_changed)
	EVT_BUTTON(kakeibo_seraddio,MyFrame::km_SerAdd_clicked)
	EVT_BUTTON(kakeibo_seradddate,MyFrame::km_SerAdd_clicked)
	EVT_BUTTON(kakeibo_seraddaccount,MyFrame::km_SerAdd_clicked)
	EVT_BUTTON(kakeibo_seraddexpense,MyFrame::km_SerAdd_clicked)
	EVT_BUTTON(kakeibo_seraddamount,MyFrame::km_SerAdd_clicked)
	EVT_BUTTON(kakeibo_serdel,MyFrame::km_SerDel_clicked)
	EVT_BUTTON(kakeibo_serexe,MyFrame::km_SerExecute_clicked)
	EVT_BUTTON(kakeibo_serclear,MyFrame::km_SerClear_clicked)
	EVT_BUTTON(kakeibo_charton,MyFrame::km_ChartOn_clicked)
	EVT_BUTTON(kakeibo_reportpublish,MyFrame::km_ReportPublish_clicked)
	EVT_BUTTON(kakeibo_jumppast,MyFrame::km_JumpBtn_clicked)
	EVT_BUTTON(kakeibo_jumpfuture,MyFrame::km_JumpBtn_clicked)
	EVT_BUTTON(kakeibo_clearperiod,MyFrame::km_ClearPeriod_clicked)
	EVT_BUTTON(kakeibo_turnstackperiod,MyFrame::km_Turn_Period_clicked)
	EVT_BUTTON(kakeibo_turnfinishperiod,MyFrame::km_Turn_Period_clicked)
	EVT_LIST_COL_CLICK(kakeibo_serdetail,MyFrame::km_SearchDetail_colclicked)
END_EVENT_TABLE() 

//---------------------------------------------------------------
// MyFrame constructor
//---------------------------------------------------------------
MyFrame::MyFrame(const wxString &title)
:wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(300,300),wxDEFAULT_FRAME_STYLE)
{
	this->SetClientSize(500,375);
	this->SetMinSize(wxSize(150,150));

	this->SetIcon(wxICON(kakeibomeister));
	//---menu bar setting
	km_MenuBar = new wxMenuBar;
	wxMenu *fileMenu = new wxMenu;
	fileMenu->Append(kakeibo_new, _("New"));
	fileMenu->Append(kakeibo_open, StrF(_T("%s\tCtrl+O"),_("Open")));
	fileMenu->Append(kakeibo_save, StrF(_T("%s\tCtrl+S"),_("Save")));
	fileMenu->Append(kakeibo_saveas, _("Save as"));
	fileMenu->AppendSeparator();
	fileMenu->Append(kakeibo_close, _("Close"));
	fileMenu->AppendSeparator();
		km_file_recent = new wxMenu;
	//fileMenu->Append(kakeibo_recentzero,_("Recently used file"));
	fileMenu->AppendSubMenu(km_file_recent,_("Recently used file"));
	fileMenu->AppendSeparator();
	fileMenu->Append(kakeibo_setprinter, _("Setting of printer"));
	fileMenu->AppendSeparator();
	fileMenu->Append(kakeibo_exit, StrF(_T("%s\tAlt+X"),_("Exit")));
	wxMenu *editMenu = new wxMenu;
	editMenu->Append(kakeibo_adddetail, StrF(_T("%s\tInsert"),_("Add In/Out")));
	editMenu->Append(kakeibo_moddetail, _("Modify"));
	editMenu->AppendSeparator();
	editMenu->Append(kakeibo_cut, StrF(_T("%s\tCtrl+X"),_("Cut")));
	editMenu->Append(kakeibo_copy, StrF(_T("%s\tCtrl+C"),_("Copy")));
	editMenu->Append(kakeibo_paste, StrF(_T("%s\tCtrl+V"),_("Paste")));
	editMenu->AppendSeparator();
	editMenu->Append(kakeibo_deldetail, StrF(_T("%s\tDel"),_("Remove")));
	editMenu->AppendSeparator();
		wxMenu *edit_favMenu = new wxMenu;
		edit_favMenu->Append(kakeibo_addfav,_("Add favorite transaction"));
		edit_favMenu->Append(kakeibo_delfav,_("Remove favorite transaction"));
		edit_favMenu->AppendSeparator();
	editMenu->Append(kakeibo_favorite,_("Favorite transaction"),edit_favMenu);
	wxMenu *viewMenu = new wxMenu;
	viewMenu->AppendRadioItem(kakeibo_viewday, StrF(_T("%s\tF5"),_("Day:")));
	viewMenu->AppendRadioItem(kakeibo_viewweek, StrF(_T("%s\tF6"),_("Week:")));
	viewMenu->AppendRadioItem(kakeibo_viewmonth, StrF(_T("%s\tF7"),_("Month:")));
	viewMenu->AppendRadioItem(kakeibo_viewsearch, StrF(_T("%s\tF8"),_("Free search:")));
	viewMenu->AppendRadioItem(kakeibo_viewreport, StrF(_T("%s\tF9"),_("Report:")));
	wxMenu *toolMenu = new wxMenu;
	toolMenu->Append(kakeibo_setgeneral, _("setting"));
	toolMenu->Append(kakeibo_setperiodicaltran, _("setting of periodical transaction"));
	toolMenu->Append(kakeibo_setexpense, _("setting of expense"));
	toolMenu->Append(kakeibo_setaccount, _("setting of account"));
	toolMenu->AppendSeparator();
	toolMenu->Append(kakeibo_import, _("Import and Export"));
	toolMenu->AppendSeparator();
	toolMenu->Append(kakeibo_calllog, _("Application log"));
	toolMenu->Append(kakeibo_dellog, _("Delete log"));
	//toolMenu->Append(kakeibo_callreport, _("Design report"));
	wxMenu *helpMenu = new wxMenu;
	helpMenu->Append(kakeibo_contents, StrF(_T("%s\tF1"),_("Contents")));
	helpMenu->Append(kakeibo_about, StrF(_T("%s\tCtrl+F1"),_("About")));
	km_MenuBar->Append(fileMenu, _("&File(&F)"));
	km_MenuBar->Append(editMenu, _("&Edit(&E)"));
	km_MenuBar->Append(viewMenu, _("&View(&V)"));
	km_MenuBar->Append(toolMenu, _("&Tool(&T)"));
	km_MenuBar->Append(helpMenu, _("&Help(&H)"));
	SetMenuBar(km_MenuBar);


	//---accelerator key setting
	wxAcceleratorEntry acce[8];
	acce[0].Set(wxACCEL_CTRL, WXK_F1, kakeibo_about);
	acce[1].Set(wxACCEL_CTRL, (int)'X', kakeibo_cut);
	acce[2].Set(wxACCEL_CTRL, (int)'C', kakeibo_copy);
	acce[3].Set(wxACCEL_CTRL, (int)'V', kakeibo_paste);
	acce[4].Set(wxACCEL_CTRL, (int)'O', kakeibo_open);
	acce[5].Set(wxACCEL_CTRL, (int)'S', kakeibo_save);
	acce[6].Set(wxACCEL_ALT, (int)'X', kakeibo_exit);
	acce[7].Set(wxACCEL_NORMAL, WXK_DELETE, kakeibo_deldetail);
	wxAcceleratorTable accel(8,acce);
	SetAcceleratorTable(accel);
	
	//---tool bar setting
	km_ToolBar = CreateToolBar();
	km_ToolBar->SetWindowStyle(km_ToolBar->GetWindowStyle() | wxTB_TEXT);
	//km_tool_Exit = new wxButton(km_ToolBar,kakeibo_close,_("Exit"));
	km_tool_Handling = new wxChoice(km_ToolBar,kakeibo_toolhandling,wxDefaultPosition,wxSize(120,-1),0,NULL);
	//km_ToolBar->AddControl(km_tool_Exit);
	km_ToolBar->AddTool(kakeibo_open,_("Open"),wxArtProvider::GetBitmap(wxART_FILE_OPEN));
	km_ToolBar->AddTool(kakeibo_save,_("Save"),wxArtProvider::GetBitmap(wxART_FILE_SAVE));
	km_ToolBar->AddTool(kakeibo_close,_("Close"),wxArtProvider::GetBitmap(wxART_QUIT));
	km_ToolBar->AddSeparator();
	km_ToolBar->AddControl(km_tool_Handling);
	km_ToolBar->AddSeparator();
	km_ToolBar->AddTool(kakeibo_adddetail,_("Add In/Out"),wxArtProvider::GetBitmap(wxART_ADD_BOOKMARK));
	km_ToolBar->AddTool(kakeibo_moddetail,_("Modify"),wxArtProvider::GetBitmap(wxART_FIND_AND_REPLACE));
	km_ToolBar->AddTool(kakeibo_deldetail,_("Remove"),wxArtProvider::GetBitmap(wxART_DEL_BOOKMARK));
	km_ToolBar->Realize();
	//---status bar setting
	km_StatusBar = CreateStatusBar();
	//---other dialog setting
	de_dialog = new DetailEditor(this);
	ed_dialog = new ExpenseDialog(this);
	ac_dialog = new AccountDialog(this);
	st_dialog = new SettingDialog(this);
	im_dialog = new ImportDialog(this);
	pt_dialog = new PeriodicalTranDialog(this);
	log_dialog = new wxLogWindow(this,_("log list"),false,false);
	rep_dialog = new ReportDialog(this);
	
	//---controls setting of main window
	km_SplitWin = new wxSplitterWindow(this, wxID_ANY,wxDefaultPosition, wxDefaultSize,wxSP_3D | wxSP_LIVE_UPDATE |wxCLIP_CHILDREN);
	km_SplitWin->SetMinimumPaneSize(180);
	mainPanel1 = new wxPanel(km_SplitWin,wxID_ANY,wxPoint(0,0),wxSize(300,300));
	mainPanel2 = new wxNotebook(km_SplitWin,kakeibo_main2,wxPoint(0,0),wxSize(-1,-1),wxNB_TOP);
	
	//---mainPanel1 setting
	km_Calender = new wxCalendarCtrl(mainPanel1,kakeibo_calendar,wxDefaultDateTime,wxPoint(-1,-1),wxSize(180,-1),wxCAL_SUNDAY_FIRST|wxCAL_SHOW_HOLIDAYS|wxCAL_SEQUENTIAL_MONTH_SELECTION);
	km_CalenYear = new wxSpinCtrl(mainPanel1,kakeibo_calyear,_T(""),wxDefaultPosition,wxSize(80,-1),wxSP_ARROW_KEYS,1,10000,2000);
	km_CalenYear->SetToolTip(_("Year"));
	km_CalenYear->SetValue(km_Calender->GetDate().GetYear());
	km_CalenMonth = new wxSpinCtrl(mainPanel1,kakeibo_calmonth,_T(""),wxDefaultPosition,wxSize(80,-1),wxSP_ARROW_KEYS,1,12,1);
	km_CalenMonth->SetToolTip(_("Month"));
	km_CalenMonth->SetValue(km_Calender->GetDate().GetMonth()+1);
	km_ReturnToday = new wxButton(mainPanel1,kakeibo_returntoday,_("Return today"),wxPoint(-1,-1),wxSize(-1,-1));
	/*km_AddDetail = new wxButton(mainPanel1, kakeibo_adddetail, _("Add In/Out"), wxPoint(-1,-1),wxSize(180,-1));
	km_ModDetail = new wxButton(mainPanel1, kakeibo_moddetail, _("Modify"), wxPoint(-1,-1),wxSize(180,-1));
	km_DelDetail = new wxButton(mainPanel1, kakeibo_deldetail, _("Remove"), wxPoint(-1,-1),wxSize(180,-1));*/
	km_JumpPast = new wxButton(mainPanel1, kakeibo_jumppast, _("To past"), wxPoint(-1,-1),wxSize(-1,-1));
	km_JumpFuture = new wxButton(mainPanel1, kakeibo_jumpfuture, _("To future"), wxPoint(-1,-1),wxSize(-1,-1));

	//---Periodical transaction controls
	mstbox = new wxStaticBox(mainPanel1,wxID_ANY,_("Periodical transaction"));
	mstsizer = new wxStaticBoxSizer(mstbox,wxVERTICAL);

	km_TurnStackPeriod = new wxButton(mainPanel1, kakeibo_turnstackperiod, _("Awaiting"), wxPoint(-1,-1),wxSize(160,-1));
	//wxStaticBox *sbox = new wxStaticBox(mainPanel1,wxID_ANY,_("Awaiting processing"));
	//wxStaticBoxSizer *sbsizer = new wxStaticBoxSizer(sbox,wxVERTICAL);
	km_InfoPeriod = new wxStaticText(mainPanel1,wxID_ANY,_T(""));
	km_StackPeriod = new wxListBox(mainPanel1,kakeibo_stockbudget,wxDefaultPosition,wxSize(165,100),0,NULL);
	km_StackPeriod->SetToolTip(_("These show the periodical transaction awaiting processing."));
	mstsizer->Add(km_TurnStackPeriod,0,wxTOP|wxLEFT);
	mstsizer->Add(km_InfoPeriod,0,wxTOP|wxLEFT);
	mstsizer->Add(km_StackPeriod,0,wxTOP|wxLEFT);
	mstsizer->Show(km_InfoPeriod,false);
	mstsizer->Show(km_StackPeriod,false);

	km_TurnFinishPeriod = new wxButton(mainPanel1, kakeibo_turnfinishperiod, _("Processed"), wxPoint(-1,-1),wxSize(160,-1));
	//wxStaticBox *sbox2 = new wxStaticBox(mainPanel1,wxID_ANY,_("Finished periodical's"));
	//wxStaticBoxSizer *sbsizer2 = new wxStaticBoxSizer(sbox2,wxVERTICAL);
	km_ClearPeriod = new wxButton(mainPanel1, kakeibo_clearperiod, _("Clear"), wxPoint(-1,-1),wxSize(160,-1));
	km_FinishPeriod = new wxListBox(mainPanel1,wxID_ANY,wxDefaultPosition,wxSize(165,100),0,NULL);
	km_FinishPeriod->SetToolTip(_("The periodical transaction which does not neet input is displayed."));
	mstsizer->AddSpacer(5);
	mstsizer->Add(km_TurnFinishPeriod,0,wxTOP|wxLEFT);
	mstsizer->Add(km_ClearPeriod,0,wxTOP|wxLEFT);
	mstsizer->Add(km_FinishPeriod,0,wxTOP|wxLEFT);
	mstsizer->Show(km_ClearPeriod,false);
	mstsizer->Show(km_FinishPeriod,false);
	mstbox->Layout();
	show_stackperiod = false;
	show_finishperiod = false;

	//mainPanel2 setting
	mainPanel2->AddPage(setup_daydetailpage(mainPanel2), _("Day:"), false);
	mainPanel2->AddPage(setup_weekdetailpage(mainPanel2), _("Week:"), false);
	mainPanel2->AddPage(setup_monthdetailpage(mainPanel2), _("Month:"), false);
	mainPanel2->AddPage(setup_searchpage(mainPanel2), _("Free search:"), false);
	//mainPanel2->AddPage(setup_chartpage(mainPanel2), _("Chart:"), false);
	mainPanel2->AddPage(setup_reportpage(mainPanel2), _("Report:"), false);
	
	//setting sizer
	wxBoxSizer *msizer1 = new wxBoxSizer(wxVERTICAL);
		wxBoxSizer *bsizer1 = new wxBoxSizer(wxHORIZONTAL);
		bsizer1->Add(km_CalenYear,0,wxLEFT,3);
		bsizer1->Add(km_CalenMonth,0,wxLEFT,5);
	msizer1->Add(km_Calender,0,wxTOP|wxLEFT,0);
	msizer1->Add(bsizer1,0,wxTOP|wxLEFT,0);
	msizer1->Add(km_ReturnToday,0,wxEXPAND|wxTOP|wxLEFT,0);
	msizer1->AddSpacer(5);
	/*msizer1->Add(km_AddDetail,0,wxTOP|wxLEFT,0);
	msizer1->Add(km_ModDetail,0,wxTOP|wxLEFT,0);
	msizer1->Add(km_DelDetail,0,wxTOP|wxLEFT,0);*/
		wxBoxSizer *bsizer2 = new wxBoxSizer(wxHORIZONTAL);
		bsizer2->Add(km_JumpPast,1,wxLEFT,0);
		bsizer2->Add(km_JumpFuture,1,wxLEFT,0);
	//msizer1->Add(km_JumpPast,0,wxTOP|wxLEFT,0);
	//msizer1->Add(km_JumpFuture,0,wxTOP|wxLEFT,0);
	msizer1->Add(bsizer2,0,wxEXPAND|wxTOP|wxLEFT,0);
	//msizer1->Add(sbsizer,0,wxTOP|wxLEFT,0);
	//msizer1->Add(sbsizer2,0,wxTOP,5);
	msizer1->Add(mstsizer,1,wxEXPAND|wxTOP|wxLEFT,0);
	mainPanel1->SetSizer(msizer1);
	mainPanel1->Layout();
	
	km_SplitWin->SplitVertically(mainPanel1,mainPanel2,185);
	listselect = -1;
	curhandling = -1;
	turnControlState(false);
	print_data = new wxPrintData;
	pagesetup_data = new wxPageSetupDialogData;
#ifdef __WINDOWS__
	wxFont font;
	font.SetFaceName(_T("MS UI Gothic"));
	km_tool_Handling->SetFont(font);
	km_DayDetail->SetFont(font);
	km_DayResult->SetFont(font);
	km_WeekDetail->SetDefaultCellFont(font);
	km_MonthDetail->SetDefaultCellFont(font);
	km_SearchDetail->SetFont(font);
#endif
}
//---------------------------------------------------------------
// MyFrame destructor
//---------------------------------------------------------------
MyFrame::~MyFrame(void)
{
	de_dialog->Close();
	ed_dialog->Close();
	ac_dialog->Close();
	st_dialog->Close();
	im_dialog->Close();
	pt_dialog->Close();
}
//---------------------------------------------------------------
// Day Detail page setup function
//---------------------------------------------------------------
wxPanel *MyFrame::setup_daydetailpage(wxNotebook *book)
{
	km_DayDetailPanel = new wxPanel(book,wxID_ANY);
	
	km_DayDetail = new wxListCtrl(km_DayDetailPanel, kakeibo_daydetail, wxPoint(-1,-1),wxDefaultSize,wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxLC_HRULES);
	km_DayResult = new wxListCtrl(km_DayDetailPanel, wxID_ANY, wxPoint(-1,-1),wxSize(-1,45),wxLC_REPORT|wxLC_NO_HEADER|wxLC_SINGLE_SEL|wxLC_VRULES|wxLC_HRULES);
	
	wxListItem itemcol;
	DetailCreateColumn(km_DayDetail)

	//setup headder, but invisible
	itemcol.SetText(_T("Label1"));
	km_DayResult->InsertColumn(0,itemcol);
	km_DayResult->SetColumnWidth(0, 120);
	itemcol.SetText(_T("Sum"));
	itemcol.SetAlign(wxLIST_FORMAT_RIGHT);
	km_DayResult->InsertColumn(1,itemcol);
	km_DayResult->SetColumnWidth(1, 100);
	itemcol.SetText(_T("Label2"));
	itemcol.SetAlign(wxLIST_FORMAT_LEFT);
	km_DayResult->InsertColumn(2,itemcol);
	km_DayResult->SetColumnWidth(2, 80);
	itemcol.SetText(_T("Budget"));
	itemcol.SetAlign(wxLIST_FORMAT_RIGHT);
	km_DayResult->InsertColumn(3,itemcol);
	km_DayResult->SetColumnWidth(3, 100);
	itemcol.SetText(_T("Label3"));
	itemcol.SetAlign(wxLIST_FORMAT_LEFT);
	km_DayResult->InsertColumn(4,itemcol);
	km_DayResult->SetColumnWidth(4, 120);
	itemcol.SetText(_T("Total income"));
	itemcol.SetAlign(wxLIST_FORMAT_RIGHT);
	km_DayResult->InsertColumn(5,itemcol);
	km_DayResult->SetColumnWidth(5, 100);
	itemcol.SetText(_T("Label4"));
	itemcol.SetAlign(wxLIST_FORMAT_LEFT);
	km_DayResult->InsertColumn(6,itemcol);
	km_DayResult->SetColumnWidth(6, 80);
	itemcol.SetText(_T("Total income"));
	itemcol.SetAlign(wxLIST_FORMAT_RIGHT);
	km_DayResult->InsertColumn(7,itemcol);
	km_DayResult->SetColumnWidth(7, 100);
	
	//setup row with fixed data
	long tmp = km_DayResult->InsertItem(0,_("sum of Income"));
	km_DayResult->SetItemData(tmp,0);
	km_DayResult->SetItem(tmp, 1, _T("0"));
	km_DayResult->SetItem(tmp, 2, _("remainder"));
	km_DayResult->SetItem(tmp, 3, _T("0"));
	km_DayResult->SetItem(tmp, 4, _("budget"));
	km_DayResult->SetItem(tmp, 5, _T("0"));
	km_DayResult->SetItem(tmp, 6, _T(""));
	km_DayResult->SetItem(tmp, 7, _T(""));
	tmp = km_DayResult->InsertItem(1,_("sum of Expenditure"));
	km_DayResult->SetItemData(tmp,1);
	km_DayResult->SetItem(tmp, 1, _T("0"));
	km_DayResult->SetItem(tmp, 2, _T(""));
	km_DayResult->SetItem(tmp, 3, _T(""));
	km_DayResult->SetItem(tmp, 4, _("diff with budget"));
	km_DayResult->SetItem(tmp, 5, _T("0"));
	km_DayResult->SetItem(tmp, 6, _T(""));
	km_DayResult->SetItem(tmp, 7, _T(""));
	
	wxBoxSizer *bsizer1 = new wxBoxSizer(wxVERTICAL);
	bsizer1->Add(km_DayDetail,1,wxEXPAND|wxTOP|wxLEFT,0);
	bsizer1->Add(km_DayResult,0,wxEXPAND|wxTOP|wxLEFT,0);
	km_DayDetailPanel->SetSizer(bsizer1);
	km_DayDetailPanel->Layout();
	return km_DayDetailPanel;
}
//---------------------------------------------------------------
// Week Detail page setup function
//---------------------------------------------------------------
wxPanel *MyFrame::setup_weekdetailpage(wxNotebook *book)
{
	km_WeekDetailPanel = new wxPanel(book,wxID_ANY);
	
	wxDateTime dt = wxDateTime::Now();
	dt = dt.Subtract(wxDateSpan(0,0,0,dt.GetWeekDay()));
	
	km_WeekDetail = new wxGrid(km_WeekDetailPanel, kakeibo_weekdetail, wxDefaultPosition, wxDefaultSize);
	km_WeekDetail->CreateGrid(255,7);
	km_WeekDetail->SetColLabelValue(0,_("Expense"));
	km_WeekDetail->SetColLabelValue(1,_("Items"));
	km_WeekDetail->SetColLabelValue(2,dt.Format(DATEFORM));
	km_WeekDetail->DisableDragGridSize();
	//km_WeekDetail->DisableDragColSize();
	km_WeekDetail->DisableDragRowSize();
	km_WeekDetail->EnableEditing(false);
	km_WeekDetail->SetColLabelSize(28);
	km_WeekDetail->SetRowLabelSize(33);
	km_WeekDetail->SetDefaultColSize(km_WeekDetail->GetDefaultColSize()+3);
	wxGridCellAttr *attr = new wxGridCellAttr();
	attr->SetAlignment(wxALIGN_RIGHT,wxALIGN_BOTTOM);
	for (int i = 2; i < 7; i++) {
		attr->IncRef();
		km_WeekDetail->SetColAttr(i, attr);
	}
	
	wxBoxSizer *bsizer1 = new wxBoxSizer(wxVERTICAL);
	bsizer1->Add(km_WeekDetail,1,wxEXPAND|wxTOP|wxLEFT,0);
	km_WeekDetailPanel->SetSizer(bsizer1);
	km_WeekDetailPanel->Layout();
	return km_WeekDetailPanel;

}
//---------------------------------------------------------------
// Month Detail page setup function
//---------------------------------------------------------------
wxPanel *MyFrame::setup_monthdetailpage(wxNotebook *book)
{
	km_MonthDetailPanel = new wxPanel(book,wxID_ANY);
	
	wxDateTime dt = wxDateTime::Now();
	dt = dt.Subtract(wxDateSpan(0,0,0,dt.GetWeekDay()));
	
	km_MonthDetail = new wxGrid(km_MonthDetailPanel, kakeibo_monthdetail, wxDefaultPosition, wxDefaultSize);
	km_MonthDetail->CreateGrid(255,7);
	km_MonthDetail->SetColLabelValue(0,_("Expense"));
	km_MonthDetail->SetColLabelValue(1,_("Items"));
	km_MonthDetail->SetColLabelValue(2,dt.Format(_T("%Y/%m")));
	km_MonthDetail->DisableDragGridSize();
	//km_MonthDetail->DisableDragColSize();
	km_MonthDetail->DisableDragRowSize();
	//km_MonthDetail->EnableEditing(false);
	km_MonthDetail->SetColLabelSize(28);
	km_MonthDetail->SetRowLabelSize(33);
	km_MonthDetail->SetDefaultColSize(km_MonthDetail->GetDefaultColSize()+3);
	wxGridCellAttr *attr = new wxGridCellAttr();
	attr->SetAlignment(wxALIGN_RIGHT,wxALIGN_BOTTOM);
	for (int i = 2; i < 7; i++) {
		attr->IncRef();
		km_MonthDetail->SetColAttr(i, attr);
	}
	
	wxBoxSizer *bsizer1 = new wxBoxSizer(wxVERTICAL);
	bsizer1->Add(km_MonthDetail,1,wxEXPAND|wxTOP|wxLEFT,0);
	km_MonthDetailPanel->SetSizer(bsizer1);
	km_MonthDetailPanel->Layout();
	return km_MonthDetailPanel;

}
//---------------------------------------------------------------
// Search page setup function
//---------------------------------------------------------------
wxPanel *MyFrame::setup_searchpage(wxNotebook *book)
{
	km_SearchPanel = new wxPanel(book,wxID_ANY);
	wxString date_items[] = {
		_("Only"),_("From"),_T("To")
	};
	wxString io_items[] = {
		_("Income"),_("Expenditure")
	};
	wxString value_items[] = {
		_T("="),_T(">"),_T(">="),_T("<"),_T("<="),_T("!=")
	};
	wxString and_items[] = {
		_T("and"),_T("or")
	};
	km_SearchSplit = new wxSplitterWindow(km_SearchPanel, wxID_ANY,wxDefaultPosition, wxDefaultSize,wxSP_3D | wxSP_LIVE_UPDATE |wxCLIP_CHILDREN);
	km_SearchSplit->SetMinimumPaneSize(240);
	km_SearchCtrl = new wxPanel(km_SearchSplit,wxID_ANY,wxPoint(0,0),wxSize(-1,240));
	km_SearchMain = new wxPanel(km_SearchSplit,wxID_ANY,wxPoint(0,0),wxSize(-1,450));
	//---Ctrl
	km_SerUseIO = new wxButton(km_SearchCtrl,kakeibo_seraddio, _("Use income and expenditure division"),wxDefaultPosition, wxDefaultSize);
	km_SerIO = new wxChoice(km_SearchCtrl,kakeibo_serio,wxDefaultPosition,wxSize(100,-1),2,io_items);
	km_SerIO->SetSelection(1);

	km_SerUseDate = new wxButton(km_SearchCtrl,kakeibo_seradddate, _("Use date"),wxDefaultPosition, wxDefaultSize);
	km_SerUseDate->SetName(_T("km_SerUseDate"));
	km_SerDateCond = new wxChoice(km_SearchCtrl,wxID_ANY,wxDefaultPosition,wxSize(70,-1),6,value_items);
	km_SerDateCond->SetSelection(0);
	km_SerDate = new wxDatePickerCtrl(km_SearchCtrl,wxID_ANY,wxDefaultDateTime,wxDefaultPosition,wxSize(120,-1),wxDP_DEFAULT|wxDP_SHOWCENTURY|wxDP_DROPDOWN);

	km_SerUseHandling = new wxButton(km_SearchCtrl,kakeibo_seraddaccount, _("Use handling"),wxDefaultPosition, wxDefaultSize);
	km_SerHandling = new wxChoice(km_SearchCtrl,wxID_ANY,wxDefaultPosition,wxSize(70,-1),3,date_items);

	km_SerUseExpense = new wxButton(km_SearchCtrl,kakeibo_seraddexpense, _("Use expense"),wxDefaultPosition, wxDefaultSize);
	km_SerExpense = new wxBitmapComboBox(km_SearchCtrl,kakeibo_serexpense,_T(""),wxDefaultPosition,wxSize(180,36),0,NULL,wxCB_READONLY);

	km_SerUserItems = new wxCheckBox(km_SearchCtrl,wxID_ANY, _("Also items"));
	km_SerItems = new wxBitmapComboBox(km_SearchCtrl,wxID_ANY,_T(""),wxDefaultPosition,wxSize(180,36),0,NULL,wxCB_READONLY);

	km_SerUseIncome = new wxButton(km_SearchCtrl,kakeibo_seraddamount, _("Use amount"),wxDefaultPosition, wxDefaultSize);
	km_SerIncome = new wxSpinCtrl(km_SearchCtrl, wxID_ANY, _T("0"),wxDefaultPosition,wxSize(120,-1),wxSP_ARROW_KEYS,0,INT_MAX,0);
	km_SerIncomeCond = new wxChoice(km_SearchCtrl,wxID_ANY,wxDefaultPosition,wxSize(55,-1),6,value_items);
	km_SerIncomeCond->SetSelection(0);

	km_SerCondList = new wxListBox(km_SearchCtrl,wxID_ANY,wxDefaultPosition,wxSize(250,170),0,NULL);
	km_SerExecute = new wxButton(km_SearchCtrl, kakeibo_serexe, _("Execute"), wxPoint(-1,-1),wxSize(160,-1));
	//km_SerAdd = new wxButton(km_SearchCtrl, kakeibo_seradd, _("Add"), wxPoint(-1,-1),wxSize(80,-1));
	km_SerDel = new wxButton(km_SearchCtrl, kakeibo_serdel, _("Remove"), wxPoint(-1,-1),wxSize(120,-1));
	km_SerAndCond = new wxChoice(km_SearchCtrl,wxID_ANY,wxDefaultPosition,wxSize(55,-1),2,and_items);
	km_SerAndCond->SetSelection(0);
	km_SerClear = new wxButton(km_SearchCtrl, kakeibo_serclear, _("Clear"), wxPoint(-1,-1),wxSize(120,-1));

	wxBoxSizer *csizer1 = new wxBoxSizer(wxHORIZONTAL);
		wxBoxSizer *csizer11 = new wxBoxSizer(wxVERTICAL);
			wxBoxSizer *csizer111 = new wxBoxSizer(wxHORIZONTAL);
			//csizer111->Add(km_SerAdd,0,wxTOP|wxLEFT,0);
			csizer111->Add(km_SerDel,0,wxTOP|wxLEFT,0);
			csizer111->Add(km_SerClear,0,wxTOP|wxLEFT,0);
		csizer11->Add(csizer111,0,wxTOP|wxLEFT,5);
		csizer11->Add(km_SerCondList,0,wxTOP|wxLEFT,5);
		csizer11->Add(km_SerExecute,0,wxTOP|wxLEFT,5);
	csizer1->Add(csizer11,0,wxTOP|wxLEFT,0);
		wxBoxSizer *csizer12 = new wxBoxSizer(wxVERTICAL);
			wxBoxSizer *csizer120 = new wxBoxSizer(wxHORIZONTAL);
			//csizer120->Add(km_SerIO,0,wxTOP|wxLEFT,0);
			csizer120->Add(km_SerAndCond,0,wxLEFT,10);
		csizer12->Add(csizer120,0,wxTOP|wxLEFT,5);
			wxBoxSizer *csizer121 = new wxBoxSizer(wxHORIZONTAL);
			csizer121->Add(km_SerUseIO,0,wxTOP,0);
			csizer121->AddSpacer(10);
			csizer121->Add(km_SerIO,0,wxTOP|wxLEFT,0);
		csizer12->AddSpacer(5);
		csizer12->Add(csizer121,0,wxTOP|wxLEFT,5);
			wxBoxSizer *csizer122 = new wxBoxSizer(wxHORIZONTAL);
			csizer122->Add(km_SerUseDate,0,wxTOP,0);
			csizer122->AddSpacer(10);
			csizer122->Add(km_SerDateCond,0,wxTOP|wxLEFT,0);
			csizer122->Add(km_SerDate,0,wxLEFT,5);
		csizer12->Add(csizer122,0,wxTOP|wxLEFT,5);
			wxBoxSizer *csizer123 = new wxBoxSizer(wxHORIZONTAL);
			csizer123->Add(km_SerUseHandling,0,wxTOP,0);
			csizer123->AddSpacer(10);
			csizer123->Add(km_SerHandling,0,wxTOP|wxLEFT,0);
		csizer12->Add(csizer123,0,wxTOP|wxLEFT,5);
			wxBoxSizer *csizer124 = new wxBoxSizer(wxHORIZONTAL);
			csizer124->Add(km_SerUseExpense,0,wxTOP,6);
			csizer124->AddSpacer(10);
			csizer124->Add(km_SerExpense,0,wxTOP|wxLEFT,0);
			csizer124->Add(km_SerUserItems,0,wxTOP|wxLEFT,10);
			csizer124->AddSpacer(3);
			csizer124->Add(km_SerItems,0,wxTOP|wxLEFT,0);
		csizer12->Add(csizer124,0,wxTOP|wxLEFT,5);
			wxBoxSizer *csizer125 = new wxBoxSizer(wxHORIZONTAL);
			csizer125->Add(km_SerUseIncome,0,wxTOP,0);
			csizer125->AddSpacer(10);
			csizer125->Add(km_SerIncomeCond,0,wxTOP|wxLEFT,0);
			csizer125->Add(km_SerIncome,0,wxLEFT,5);
		csizer12->AddSpacer(5);
		csizer12->Add(csizer125,0,wxTOP|wxLEFT,5);
	csizer1->Add(csizer12,0,wxTOP|wxLEFT,0);
	km_SearchCtrl->SetSizer(csizer1);
	km_SearchCtrl->Layout();
	//---Main
	km_SearchDetail = new wxListCtrl(km_SearchMain, kakeibo_serdetail, wxPoint(-1,-1),wxSize(-1,145),wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxLC_HRULES);
	wxListItem itemcol;
	DetailCreateColumn(km_SearchDetail)
	wxBoxSizer *csizer2 = new wxBoxSizer(wxHORIZONTAL);
	csizer2->Add(km_SearchDetail,1,wxEXPAND|wxTOP|wxLEFT,0);
	km_SearchMain->SetSizer(csizer2);
	km_SearchMain->Layout();

	wxBoxSizer *bsizer1 = new wxBoxSizer(wxVERTICAL);
	bsizer1->Add(km_SearchSplit,1,wxEXPAND|wxTOP|wxLEFT,0);
	km_SearchPanel->SetSizer(bsizer1);
	km_SearchPanel->Layout();

	km_SearchSplit->SplitHorizontally(km_SearchCtrl,km_SearchMain,250);

	return km_SearchPanel;

}
//---------------------------------------------------------------
// Chart page setup function
//---------------------------------------------------------------
wxPanel *MyFrame::setup_chartpage(wxNotebook *book)
{
	km_ChartPanel = new wxPanel(book,wxID_ANY);
	wxString src_items[] = {
		_("Today"),_("This week"),_("This month"),_("This searches")
	};
	km_ChartCtrl = new wxPanel(km_ChartPanel,wxID_ANY,wxDefaultPosition,wxSize(-1,75));
	km_ChartMain = new ChartPicker(km_ChartPanel,wxID_ANY,HORIZONTAL,wxDefaultPosition,wxSize(700,525));

	wxStaticText *label1 = new wxStaticText(km_ChartCtrl,wxID_ANY,_("Data source:"));
	km_ChartSource = new wxChoice(km_ChartCtrl,wxID_ANY,wxDefaultPosition,wxSize(120,-1),4,src_items);
	km_ChartSource->SetSelection(0);
	km_ChartOn = new wxButton(km_ChartCtrl, kakeibo_charton, _("Show"), wxPoint(-1,-1),wxSize(80,-1));

	wxBoxSizer *csizer1 = new wxBoxSizer(wxHORIZONTAL);
	csizer1->Add(label1,0,wxTOP,3);
	csizer1->Add(km_ChartSource,0,wxLEFT,5);
	csizer1->Add(km_ChartOn,0,wxLEFT,10);
	km_ChartCtrl->SetSizer(csizer1);
	km_ChartCtrl->Layout();

	wxBoxSizer *bsizer1 = new wxBoxSizer(wxVERTICAL);
	bsizer1->Add(km_ChartCtrl,0,wxTOP|wxLEFT,0);
	bsizer1->Add(km_ChartMain,1,wxEXPAND|wxTOP|wxLEFT,0);
	km_ChartPanel->SetSizer(bsizer1);
	km_ChartPanel->Layout();
	return km_ChartPanel;

}
//---------------------------------------------------------------
// Report page setup function
//---------------------------------------------------------------
wxPanel *MyFrame::setup_reportpage(wxNotebook *book)
{
	km_ReportPanel = new wxPanel(book,wxID_ANY);
	wxString src_items[] = {
		_("Today"),_("This week"),_("This month"),_("This searches")
	};
	wxString opt_items[] = {
		_("draw a frame around a margin"),_("show all handling"),_("don't show expense, what's transaction is zero"),
		_("draw this week and before-after 1 week, when source is weekly")
	};
	int opt_size = sizeof(opt_items) / sizeof(wxString);

	wxStaticText *label1 = new wxStaticText(km_ReportPanel,wxID_ANY,_("Data source:"));
	km_ReportSource = new wxChoice(km_ReportPanel,wxID_ANY,wxDefaultPosition,wxSize(120,-1),4,src_items);
	km_ReportSource->SetSelection(0);

	wxStaticText *label4 = new wxStaticText(km_ReportPanel,wxID_ANY,_("Title of report:"));
	km_ReportTitle = new wxTextCtrl(km_ReportPanel, wxID_ANY, _T(""),wxDefaultPosition,wxSize(350,-1));

	wxStaticText *label2 = new wxStaticText(km_ReportPanel,wxID_ANY,_("Header:"));
	km_ReportEnableHeader = new wxCheckBox(km_ReportPanel,kakeibo_enableheader,_("Enable Header"));
	for (int i = 0; i < 3; i++) {
		km_ReportHeader[i] = new wxTextCtrl(km_ReportPanel, wxID_ANY, _T(""),wxDefaultPosition,wxSize(150,-1));
	}
	km_ReportLineHeader = new wxCheckBox(km_ReportPanel,wxID_ANY,_("Draw a line in the header"));

	wxStaticText *label3 = new wxStaticText(km_ReportPanel,wxID_ANY,_("Footer:"));
	km_ReportEnableFooter = new wxCheckBox(km_ReportPanel,kakeibo_enablefooter,_("Enable Footer"));
	for (int i = 0; i < 3; i++) {
		km_ReportFooter[i] = new wxTextCtrl(km_ReportPanel, wxID_ANY, _T(""),wxDefaultPosition,wxSize(150,-1));
	}
	km_ReportLineFooter = new wxCheckBox(km_ReportPanel,wxID_ANY,_("Draw a line in the footer"));

	wxString expstr = StrF(_T("%s\n%s\n%s\n%s\n%s\n"),_(" %B : Book title"),
		_(" %T : Report additional title"),
		_(" %p : current page number"),
		_(" %P : total page number"),
		_(" %D : date of today"));
	wxStaticText *label_headerexplain = new wxStaticText(km_ReportPanel,wxID_ANY,expstr,wxDefaultPosition,wxDefaultSize,wxBORDER_STATIC);
	label_headerexplain->SetBackgroundColour(*wxWHITE);

	wxStaticText *label5 = new wxStaticText(km_ReportPanel,wxID_ANY,_("Option"));
	km_ReportOptions = new wxCheckListBox(km_ReportPanel,wxID_ANY,wxDefaultPosition,wxSize(450,75),opt_size,opt_items);
	km_ReportPublish = new wxButton(km_ReportPanel, kakeibo_reportpublish, _("Publish"), wxPoint(-1,-1),wxSize(80,-1));

	wxBoxSizer *bsizer1 = new wxBoxSizer(wxVERTICAL);
		wxBoxSizer *bsizer2 = new wxBoxSizer(wxHORIZONTAL);
		bsizer2->Add(label1,0,wxTOP|wxLEFT,0);
		bsizer2->Add(km_ReportSource,0,wxLEFT,5);
	bsizer1->Add(bsizer2,0,wxTOP,5);
		wxBoxSizer *bsizer5 = new wxBoxSizer(wxHORIZONTAL);
		bsizer5->Add(label4,0,wxTOP|wxLEFT,0);
		bsizer5->Add(km_ReportTitle,0,wxLEFT,5);
	bsizer1->Add(bsizer5,0,wxTOP,10);
	//---header
		wxBoxSizer *bsizer6 = new wxBoxSizer(wxHORIZONTAL);
			wxBoxSizer *bsizer7 = new wxBoxSizer(wxVERTICAL);
			bsizer7->Add(label2,0,wxTOP,15);
			bsizer7->Add(km_ReportEnableHeader,0,wxTOP|wxLEFT,0);
				wxBoxSizer *bsizer3 = new wxBoxSizer(wxHORIZONTAL);
				bsizer3->Add(km_ReportHeader[0],0,wxTOP|wxLEFT,0);
				bsizer3->Add(km_ReportHeader[1],0,wxLEFT,5);
				bsizer3->Add(km_ReportHeader[2],0,wxLEFT,5);
			bsizer7->Add(bsizer3,0,wxTOP|wxLEFT,0);
			bsizer7->Add(km_ReportLineHeader,0,wxTOP|wxLEFT,0);
			//---footer
			bsizer7->Add(label3,0,wxTOP,15);
			bsizer7->Add(km_ReportEnableFooter,0,wxTOP|wxLEFT,0);
				wxBoxSizer *bsizer4 = new wxBoxSizer(wxHORIZONTAL);
				bsizer4->Add(km_ReportFooter[0],0,wxTOP|wxLEFT,0);
				bsizer4->Add(km_ReportFooter[1],0,wxLEFT,5);
				bsizer4->Add(km_ReportFooter[2],0,wxLEFT,5);
			bsizer7->Add(bsizer4,0,wxTOP|wxLEFT,0);
			bsizer7->Add(km_ReportLineFooter,0,wxTOP|wxLEFT,0);
		bsizer6->Add(bsizer7,0,wxTOP,0);
		bsizer6->AddSpacer(10);
		bsizer6->Add(label_headerexplain,0,wxTOP,35);
	bsizer1->Add(bsizer6,0,wxTOP,0);
	//---other options
	bsizer1->Add(label5,0,wxTOP,10);
	bsizer1->Add(km_ReportOptions,0,wxTOP|wxLEFT,0);
	bsizer1->AddSpacer(15);
	bsizer1->Add(km_ReportPublish,0,wxRIGHT|wxALIGN_RIGHT,15);
	km_ReportPanel->SetSizer(bsizer1);
	km_ReportPanel->Layout();
	return km_ReportPanel;

}
//---------------------------------------------------------------
// File menu - New event
//---------------------------------------------------------------
void MyFrame::fileMenu_New_clicked(wxCommandEvent &event)
{
	if (wxGetApp().SQLDB().IsOpen()) {
		Close_File();
	}
	wxString tmpfilepath = wxFileName::CreateTempFileName(_T("t"));
	wxGetApp().SQLDB().Open(tmpfilepath);
	wxGetApp().SQLDB().Begin();
	//---create default tables
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_BUDGET);
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_TOTAL);
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_EXPENSE);
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_ITEMS);
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_ACCOUNT);
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_COUNTER);
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_CONFIG);
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_PERIOD);
	wxGetApp().SQLDB().ExecuteUpdate(CREATE_TBL_RESERVED);
	//wxGetApp().SQLDB().ExecuteUpdate(CREATE_VIEW_BUDGET);
	wxGetApp().SQLDB().ExecuteUpdate(_T("insert into db_counter values(0, 0, 0, 0, 1);"));
	//---initialize base setting
	st_dialog->SetInitialMode(true);
	st_dialog->BindData_Setting(wxGetApp().AppDB.AppSetting);
	st_dialog->CenterOnParent();
	if (st_dialog->ShowModal() == setting_ok) {
		DB_setting db = st_dialog->GetData_Setting();
		wxGetApp().AppDB.AppSetting = st_dialog->GetData_Setting();

		//---register default handling "Cash"
		wxString accname = _("Cash");
		wxGetApp().SQLDB().ExecuteUpdate(StrF(_T("insert into db_account(ac_name,ac_initial) values('%s',%d);"),
			accname.c_str(),db.GetRemainder()));
		wxGetApp().AppDB.CountAccount += 1;
		//---update remainder
		int tmpid = 0;
		wxString sql = _T("select ac_id from db_account;");
		wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
		while (rset.NextRow()) {
			tmpid = rset.GetInt(0);
			break;
		}
		sql = wxString::Format(_T("insert into db_total values ( '%s', %d, %d, %d, %d );"),
			db.GetStartDate().Format(DATEFORM).c_str(),tmpid,0,0,db.GetRemainder());
		wxGetApp().SQLDB().ExecuteUpdate(sql);
		DB_total totdb;
		totdb.SetIncome(0);
		totdb.SetExpenditure(0);
		totdb.SetRemainder(db.GetRemainder());
		ChangeRowTotal(totdb);
		//update config
		wxGetApp().SQLDB().ExecuteQuery(StrF(_T("insert into db_config values('%s','%s');"),
			_T("cf_startdate"),db.GetStartDate().Format(DATEFORM).c_str()));
		wxGetApp().SQLDB().ExecuteQuery(StrF(_T("insert into db_config values('%s','1');"),
			_T("cf_settlingday")));
		wxGetApp().SQLDB().ExecuteQuery(StrF(_T("insert into db_config values('%s','0');"),
			_T("cf_settlinglastday")));
		wxGetApp().SQLDB().ExecuteQuery(StrF(_T("insert into db_config values('%s','12');"),
			_T("cf_settlingmonth")));
		wxGetApp().SQLDB().ExecuteQuery(StrF(_T("insert into db_config values('%s',' ');"),
			_T("cf_username")));
		wxGetApp().SQLDB().ExecuteQuery(StrF(_T("insert into db_config values('%s',' ');"),
			_T("cf_bookname")));
		//---set data in db_config
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_startdate")),wxGetApp().AppDB.AppSetting.GetStartDate().Format(DATEFORM));
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_settlingday")),wxGetApp().AppDB.AppSetting.GetSettlingDay());
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_settlinglastday")),wxGetApp().AppDB.AppSetting.GetSettlingLastDay());
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_settlingmonth")),wxGetApp().AppDB.AppSetting.GetSettlingMonth());
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_username")),wxGetApp().AppDB.AppSetting.GetUserNames());
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_bookname")),wxGetApp().AppDB.AppSetting.GetBookName());
	}else if (st_dialog->GetReturnCode() == setting_can) {
		wxGetApp().SQLDB().Rollback();
		return;
	}
	wxGetApp().SetFilePath(tmpfilepath);
	wxGetApp().SetTempFilePath(tmpfilepath);
	wxGetApp().SetNewFlag(true);
	InsertPresetData();
	if (wxGetApp().AppDB.AppSetting.GetBookName().IsEmpty()) {
		this->SetTitle(wxString::Format(_T("%s - %s"),_("No title"),APPTITLE));
	}else{
		wxFileName fname(wxGetApp().GetFilePath());
		SetKakeiboTitle(fname,wxGetApp().AppDB.AppSetting.GetBookName());
	}
	UpdateControl();
	turnControlState(true);
	km_Calender->SetDate(wxDateTime::Now());
}
//---------------------------------------------------------------
// File menu - Open event
//---------------------------------------------------------------
void MyFrame::fileMenu_Open_clicked(wxCommandEvent &event)
{
	wxFileDialog dialog(this,_("Please choose a file."),_T(""),_T(""),
		_("KakeiboMeister file (*.kak)|*.kak;"));
	if (wxGetApp().SQLDB().IsOpen() && wxGetApp().IsChanged()) {
		int ret = wxMessageBox(_("This file is changed.\nDo you really continue?"),APPTITLE,
			wxYES_NO|wxICON_QUESTION,this);
		if (ret == wxNO) {
			return;
		}
		if (wxGetApp().IsNewFile()) {
			wxGetApp().SQLDB().Close();
			wxRemoveFile(wxGetApp().GetFilePath());
		}else{
			wxGetApp().SQLDB().Rollback();
			wxGetApp().SQLDB().Close();
		}
	}
#ifdef __WIN64_DEBUG_ERROR_EVID
	wxString pp = wxGetTextFromUser(_T("input"),APPTITLE);
	if (!pp.IsEmpty()) {
		Open_File(pp);
#else
	if (dialog.ShowModal() == wxID_OK) {
		Open_File(dialog.GetPath());
#endif
	}
}
//---------------------------------------------------------------
// File menu - Save/Save as event
//---------------------------------------------------------------
void MyFrame::fileMenu_Save_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	if ((event.GetId() == kakeibo_saveas) || (wxGetApp().IsNewFile())) {
		Save_File(false);
	}else{
		Save_File(true);
	}
}
//---------------------------------------------------------------
// File menu - Close event
//---------------------------------------------------------------
void MyFrame::fileMenu_Close_clicked(wxCommandEvent &event)
{
	Close_File();
}
//---------------------------------------------------------------
// File menu - Recent file clicked event
//---------------------------------------------------------------
void MyFrame::fileMenu_Recent_clicked(wxCommandEvent &event)
{
	wxMenuItem *item = (wxMenuItem*)(event.GetEventObject());
	int index = event.GetId() - (int)kakeibo_recent01;
	Open_File(wxGetApp().AppDB.AppSetting.GetRecent(index));
}
//---------------------------------------------------------------
// File menu - Set printer event
//---------------------------------------------------------------
void MyFrame::fileMenu_SetPrinter_clicked(wxCommandEvent &event)
{
	wxPageSetupDialog dialog(this,pagesetup_data);
	if (dialog.ShowModal() == wxID_OK) {
		*pagesetup_data = dialog.GetPageSetupData();
		*print_data = pagesetup_data->GetPrintData();
	}
}
//---------------------------------------------------------------
// File menu - Exit event
//---------------------------------------------------------------
void MyFrame::fileMenu_Exit_clicked(wxCommandEvent &event)
{
	if (Close_File() == 0)
	Close(true);
}
//---------------------------------------------------------------
// Edit menu - Cut event
//---------------------------------------------------------------
void MyFrame::editMenu_Cut_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	if (listselect < 0) return;
	clip_dbbudget.clear();
	clip_dbbudget.push_back(dbbudget.at(listselect));
	//same as km_DelDetail_clicked
	dbbudget.at(listselect).SetFlag(del_mt);

	UpdateDB();
	if (mainPanel2->GetSelection() == 0) {
		ChangePage(km_Calender->GetDate(),curhandling);
	}else{
		GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
	}

}
//---------------------------------------------------------------
// Edit menu - Copy event
//---------------------------------------------------------------
void MyFrame::editMenu_Copy_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	if (listselect < 0) return;
	clip_dbbudget.clear();
	clip_dbbudget.push_back(dbbudget.at(listselect));
}
//---------------------------------------------------------------
// Edit menu - Paste event
//---------------------------------------------------------------
void MyFrame::editMenu_Paste_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	if (clip_dbbudget.size() == 0) return;
	for (int i = 0; i < (int)clip_dbbudget.size(); i++) {
		clip_dbbudget.at(i).SetFlag(add_mt);
		clip_dbbudget.at(i).SetDate(km_Calender->GetDate());
		clip_dbbudget.at(i).SetId(wxGetApp().AppDB.GetLastIdOfBudget(
			km_Calender->GetDate(),clip_dbbudget.at(i).GetIO(),
			clip_dbbudget.at(i).GetHandling()));
		dbbudget.push_back(clip_dbbudget.at(i));
	}
	UpdateDB();
	if (mainPanel2->GetSelection() == 0) {
		ChangePage(km_Calender->GetDate(),curhandling);
	}else{
		GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
	}
	clip_dbbudget.clear();
}
//---------------------------------------------------------------
// Edit menu - Add favorite transaction event
//---------------------------------------------------------------
void MyFrame::editMenu_AddFavorite_clicked(wxCommandEvent &event)
{
	wxString sql = StrF(WXSQL_GET_PERIOD_CNT_IF_TIMING,3);
	int favcnt = wxGetApp().SQLDB().ExecuteScalar(sql);
	if (favcnt >= 20) {
		const wxString mes = _("You can not register favorite transaction over 20.");
		wxMessageBox(mes,APPTITLE,wxOK|wxICON_EXCLAMATION,this);
		return;
	}

	de_dialog->SetExpense(in_it);
	de_dialog->SetItems(0);
	de_dialog->SetAccount(-1);
	de_dialog->ChangeEnable(-1,true);
	de_dialog->ClearControl();
	de_dialog->CenterOnParent();
	if (de_dialog->ShowModal() == detaile_ok) {
		DB_periodical newrow;
		DB_day db;
		newrow.SetFlag(add_mt);

		db.SetId(-1);
		db.SetIO((InoutType)de_dialog->GetDataIncome());
		db.SetExpense(de_dialog->GetDataExpense());
		db.SetItems(de_dialog->GetDataItems());
		db.SetHandling(de_dialog->GetDataHandling());
		if (de_dialog->GetDataIncome() == 0) {
			db.SetIncome(de_dialog->GetDataValue());
			db.SetExpenditure(0);
		}else{
			db.SetIncome(0);
			db.SetExpenditure(de_dialog->GetDataValue());
		}
		db.SetMemo(de_dialog->GetDataMemo());
		newrow.SetBudget(db);
		//---set 3 to pr_periodtype (favorite transaction)
		newrow.SetTiming(3);

		//---set favorite transaction in internal data and db_period
		wxGetApp().AppDB.AppSetting.AddPeriod(newrow);
		wxGetApp().AppDB.AddPeriod(newrow);
		db_menufavorites.Add(newrow);

		//---register menu bar
		SetFavoriteMenu(newrow);
		/*wxMenuBar *menubar = GetMenuBar();
		wxMenu *menu = menubar->GetMenu(1);
		wxMenuItem *menuitem = menu->FindItem(kakeibo_favorite);
		wxMenu *cmenu = menuitem->GetSubMenu();
		Msgbox(cmenu->GetLabelText(kakeibo_addfav)+IntToStr(cmenu->GetMenuItemCount()),this);
		//---===set expense name and item name of expense
		wxString labelname;
		int favcnt = 1;
		wxString sql = StrF(WXSQL_GET_EXPENSE_AND_ITEM,
			newrow.GetBudget().GetExpense(),newrow.GetBudget().GetItems());
		wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
		while (rset.NextRow()) {
			labelname = rset.GetString(0) + _T(" - ") +	rset.GetString(1) + _T(": ");
		}
		labelname += db.GetMemo();
		sql = StrF(WXSQL_GET_PERIOD_CNT_IF_TIMING,3);
		favcnt = wxGetApp().SQLDB().ExecuteScalar(sql);
		
		cmenu->Append(kakeibo_favzero+favcnt,labelname);

		wxGetApp().SetChangeFlag(true);*/
		
	}

}
//---------------------------------------------------------------
// Edit menu - Remove favorite transaction event
//---------------------------------------------------------------
void MyFrame::editMenu_DelFavorite_clicked(wxCommandEvent &event)
{
	//---make choice item 
	wxArrayString labelnames;
	for (int i = 0; i < (int)db_menufavorites.GetCount(); i++) {
		wxString sql = StrF(WXSQL_GET_EXPENSE_AND_ITEM,
			db_menufavorites.Item(i).GetBudget().GetExpense(),
			db_menufavorites.Item(i).GetBudget().GetItems());
		wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
		wxString label;
		while (rset.NextRow()) {
			label = rset.GetString(0) + _T(" - ") +	rset.GetString(1) + _T(": ");
		}
		labelnames.Add(label+db_menufavorites.Item(i).GetBudget().GetMemo());
	}

	wxSingleChoiceDialog *dlg = new wxSingleChoiceDialog(this,_("Please select transaction to remove."),APPTITLE,
		labelnames);
	if (dlg->ShowModal() == wxID_OK) {
		if (wxMessageBox(_("Do you really remove selected transaction ?"),APPTITLE,wxYES_NO,this) == wxNO) {
			return;
		}
		int targetID = kakeibo_favzero + dlg->GetSelection() + 1;
		int index = dlg->GetSelection();
		if (((index >= 0) && (index <= 19)) || 
			((db_menufavorites.GetCount() > 0) && (db_menufavorites.GetCount() <= 20))
		) {
			wxMenuBar *menubar = GetMenuBar();
			wxMenu *menu = menubar->GetMenu(1);
			wxMenuItem *menuitem = menu->FindItem(kakeibo_favorite);
			wxMenu *cmenu = menuitem->GetSubMenu();
			cmenu->Remove(targetID);
			db_menufavorites.RemoveAt(index);
		}
	}
}
//---------------------------------------------------------------
// Edit menu - Add favorite transaction to day's transaction event
//---------------------------------------------------------------
void MyFrame::editMenu_GoFavorite_clicked(wxCommandEvent &event)
{
	
	int targetID = event.GetId();
	int index = event.GetId() - kakeibo_favzero - 1;

	//---register favorite transaction to db_budgets
	wxString arr[7];
	int imageid[2];
	DB_day db = db_menufavorites.Item(index).GetBudget();
	wxString sql;
	int valueforlog = 0;
	//for listctrl
	arr[0] = km_Calender->GetDate().Format(DATEFORM);
	arr[1] = wxGetApp().AppDB.GetExpense(db.GetExpense(),
		db.GetIO()).GetName();
	imageid[0] = wxGetApp().AppDB.GetExpense(db.GetExpense(),
		db.GetIO()).GetImage();
	arr[2] = wxGetApp().AppDB.GetItems(db.GetItems(),
		db.GetExpense()).GetName();
	imageid[1] = wxGetApp().AppDB.GetItems(db.GetItems(),
		db.GetExpense()).GetImage();
	int acc = db.GetHandling();
	arr[3] = wxGetApp().AppDB.GetAccount(acc).GetName();
	if (db.GetIO() == 0) {
		arr[4] = IntToStr(db.GetIncome());
		arr[5] = _T(" ");
		valueforlog += db.GetIncome();
	}else{
		arr[4] = _T(" ");
		arr[5] = IntToStr(db.GetExpenditure());
		valueforlog -= db.GetIncome();
	}
	arr[6] = db.GetMemo();
	if (acc == curhandling) {
		InsertRow(km_DayDetail,arr,sizeof(arr),imageid,2);
	}
	//for DB (set up remainning items
	db.SetId(wxGetApp().AppDB.GetLastIdOfBudget(wxDateTime::Now(),db.GetIO(),db.GetHandling()));
	db.SetFlag(add_mt);
	db.SetDate(km_Calender->GetDate());
	//---make linked transaction at now
	if ((db.GetExpense() == 3) || (db.GetExpense() == 4)) {
		db.SetExtra(StrF(_T("l%s:"),
			GenerateLinkId(db.GetDate(),db.GetIO(),db.GetHandling(),db.GetId()).c_str()));
	}
	dbbudget.push_back(db);
	
	UpdateLinkedBudget(db);
	UpdateDB();
	if (mainPanel2->GetSelection() == 0) {
		ChangePage(km_Calender->GetDate(),curhandling);
	}else{
		GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
	}
	/*LOG*/wxGetApp().WriteLog(StrF(_("Added the data at %s (%s, %s - %s: %+d)"),
		arr[0].c_str(), arr[3].c_str(),arr[1].c_str(), arr[2].c_str(), valueforlog));

}
//---------------------------------------------------------------
// View menu - Change tab event
//---------------------------------------------------------------
void MyFrame::viewMenu_Tabs_clicked(wxCommandEvent &event)
{
	switch (event.GetId()) {
	case kakeibo_viewday:
		mainPanel2->SetSelection(0);
		break;
	case kakeibo_viewweek:
		mainPanel2->SetSelection(1);
		break;
	case kakeibo_viewmonth:
		mainPanel2->SetSelection(2);
		break;
	case kakeibo_viewsearch:
		mainPanel2->SetSelection(3);
		break;
	case kakeibo_viewreport:
		mainPanel2->SetSelection(4);
		break;
	}
}
//---------------------------------------------------------------
// Tool menu - Show Setting dialog event
//---------------------------------------------------------------
void MyFrame::toolMenu_SetGeneral_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	st_dialog->SetInitialMode(false);
	st_dialog->SetAccount();
	st_dialog->BindData_Setting(wxGetApp().AppDB.AppSetting);
	st_dialog->CenterOnParent();
	if (st_dialog->ShowModal() == setting_ok) {
		//wxGetApp().AppDB.AppSetting.Copy(st_dialog->GetData_Setting());
		wxGetApp().AppDB.AppSetting = st_dialog->GetData_Setting();

		/*wxGetApp().SQLDB().ExecuteUpdate(StrF(_T("update db_config set cf_value = '%s' where cf_name = '%s';"),
			wxGetApp().AppDB.AppSetting.GetStartDate().Format(DATEFORM).c_str(),_T("cf_startdate")));
		wxGetApp().SQLDB().ExecuteUpdate(StrF(_T("update db_config set cf_value = '%d' where cf_name = '%s';"),
			wxGetApp().AppDB.AppSetting.GetSettlingDay(),_T("cf_settlingday")));
		wxGetApp().SQLDB().ExecuteUpdate(StrF(_T("update db_config set cf_value = '%d' where cf_name = '%s';"),
			(wxGetApp().AppDB.AppSetting.GetSettlingLastDay() ? 1 : 0),_T("cf_settlinglastday")));
		wxGetApp().SQLDB().ExecuteUpdate(StrF(_T("update db_config set cf_value = '%d' where cf_name = '%s';"),
			wxGetApp().AppDB.AppSetting.GetSettlingMonth(),_T("cf_settlingmonth")));*/
		//---set data in db_config
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_startdate")),wxGetApp().AppDB.AppSetting.GetStartDate().Format(DATEFORM));
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_settlingday")),wxGetApp().AppDB.AppSetting.GetSettlingDay());
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_settlinglastday")),wxGetApp().AppDB.AppSetting.GetSettlingLastDay());
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_settlingmonth")),wxGetApp().AppDB.AppSetting.GetSettlingMonth());
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_username")),wxGetApp().AppDB.AppSetting.GetUserNames());
		wxGetApp().AppDB.AppSetting.WriteConfig(StrF(_T("cf_bookname")),wxGetApp().AppDB.AppSetting.GetBookName());
		int maxcnt = 0;
		/*maxcnt = wxGetApp().AppDB.AppSetting.GetPeriodCount();
		for (int i = 0; i < maxcnt; i++) {
			switch (wxGetApp().AppDB.AppSetting.GetPeriod(i).GetFlag()) {
			case add_mt:
				wxGetApp().AppDB.AddPeriod(wxGetApp().AppDB.AppSetting.GetPeriod(i));
				break;
			case mod_mt:
				wxGetApp().AppDB.SetPeriod(
					wxGetApp().AppDB.AppSetting.GetPeriod(i),
					wxGetApp().AppDB.AppSetting.GetPeriod(i));
				break;
			case del_mt:
				wxString sql = StrF(_T("delete from db_period where pr_id = %d;"),
					wxGetApp().AppDB.AppSetting.GetPeriod(i).GetId());
				wxGetApp().SQLDB().ExecuteUpdate(sql);
				break;
			}
		}*/
		//---set budgets in db_reserved
		maxcnt = wxGetApp().AppDB.AppSetting.GetBudgetCount();
		for (int i = 0; i < maxcnt; i++) {
			switch (wxGetApp().AppDB.AppSetting.GetBudget(i).GetFlag()) {
			case add_mt:
				wxGetApp().AppDB.AddReserved(wxGetApp().AppDB.AppSetting.GetBudget(i));
				break;
			case mod_mt:
				wxGetApp().AppDB.SetReserved(
					wxGetApp().AppDB.AppSetting.GetBudget(i),
					wxGetApp().AppDB.AppSetting.GetBudget(i));
				break;
			case del_mt:
				wxString sql = StrF(_T("delete from db_reserved where rs_id = %d;"),
					wxGetApp().AppDB.AppSetting.GetBudget(i).GetId());
				wxGetApp().SQLDB().ExecuteUpdate(sql);
				break;
			}
		}

		wxFileName fname(wxGetApp().GetFilePath());
		SetKakeiboTitle(fname,wxGetApp().AppDB.AppSetting.GetBookName());
		wxGetApp().SetChangeFlag(true);
		//---refresh also each tab contents
		if (mainPanel2->GetSelection() == 0) {
			ChangePage(km_Calender->GetDate(),curhandling);
		}else{
			ChangePage(km_Calender->GetDate(),curhandling);
			GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
		}
		//---Refresh setting from DB
		wxGetApp().AppDB.AppSetting.LoadDB();
	}
}
//---------------------------------------------------------------
// Tool menu - Show periodical transaction dialog event
//---------------------------------------------------------------
void MyFrame::toolMenu_SetPeriodical_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	pt_dialog->BindData_Periodical(wxGetApp().AppDB.AppSetting.GetPeriodAll());
	pt_dialog->CenterOnParent();
	if (pt_dialog->ShowModal() == periodicaltran_ok) {
		wxGetApp().AppDB.AppSetting.SetPeriodAll(pt_dialog->GetData_Periodical());
		//---set periodical transaction in db_period
		int maxcnt = wxGetApp().AppDB.AppSetting.GetPeriodCount();
		for (int i = 0; i < maxcnt; i++) {
			if (wxGetApp().AppDB.AppSetting.GetPeriod(i).GetTiming() == 3) continue;
			switch (wxGetApp().AppDB.AppSetting.GetPeriod(i).GetFlag()) {
			case add_mt:
				wxGetApp().AppDB.AddPeriod(wxGetApp().AppDB.AppSetting.GetPeriod(i));
				break;
			case mod_mt:
				wxGetApp().AppDB.SetPeriod(
					wxGetApp().AppDB.AppSetting.GetPeriod(i),
					wxGetApp().AppDB.AppSetting.GetPeriod(i));
				break;
			case del_mt:
				wxString sql = StrF(_T("delete from db_period where pr_id = %d;"),
					wxGetApp().AppDB.AppSetting.GetPeriod(i).GetId());
				wxGetApp().SQLDB().ExecuteUpdate(sql);
				break;
			}
		}
		wxGetApp().SetChangeFlag(true);
	}
}
//---------------------------------------------------------------
// Tool menu - Show expense and item dialog event
//---------------------------------------------------------------
void MyFrame::toolMenu_SetExpense_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	wxString sql = _T("select * from db_expense;");
	wxSQLite3ResultSet tbl = wxGetApp().SQLDB().ExecuteQuery(sql);
	ed_dialog->BindData_Expense(tbl);
	sql = _T("select * from db_items;");
	tbl = wxGetApp().SQLDB().ExecuteQuery(sql);
	ed_dialog->BindData_Items(tbl);
	ed_dialog->BindData_Icon(wxGetApp().icoDList);
	ed_dialog->ClearControl();
	ed_dialog->CenterOnParent();
	if (ed_dialog->ShowModal() == expense_ok) {
		vector <DB_expense> dbs;
		vector <DB_items> dbi;
		int i;
		//---add expense and items
		dbs = ed_dialog->GetChangedExpense(add_mt);
		for (i = 0; i < (int)dbs.size(); i++) {
			wxGetApp().AppDB.AddExpense(dbs.at(i));
			//count up
			wxGetApp().AppDB.CountExpense++;
			wxGetApp().SQLDB().ExecuteUpdate(wxString::Format(_T("update db_counter set ct_expense = %d"),wxGetApp().AppDB.CountExpense));
		}
		dbs.clear();
		dbi = ed_dialog->GetChangedItems(add_mt);
		for (i = 0; i < (int)dbi.size(); i++) {
			wxGetApp().AppDB.AddItems(dbi.at(i));
			//count up
			wxGetApp().AppDB.CountItems++;
			wxGetApp().SQLDB().ExecuteUpdate(wxString::Format(_T("update db_counter set ct_items = %d"),wxGetApp().AppDB.CountItems));
		}
		dbi.clear();
		//---modify expense and items
		dbs = ed_dialog->GetChangedExpense(mod_mt);
		for (i = 0; i < (int)dbs.size(); i++) {
			wxGetApp().AppDB.SetExpense(dbs.at(i).GetId(),dbs.at(i));
		}
		dbs.clear();
		dbi = ed_dialog->GetChangedItems(mod_mt);
		for (i = 0; i < (int)dbi.size(); i++) {
			wxGetApp().AppDB.SetItems(dbi.at(i),dbi.at(i));
		}
		dbi.clear();
		//---delele expense and items
		dbs = ed_dialog->GetChangedExpense(del_mt);
		for (i = 0; i < (int)dbs.size(); i++) {
			wxString sql = wxString::Format(_T("delete from db_expense where ex_id = %d;"),
				dbs.at(i).GetId());
			wxGetApp().SQLDB().ExecuteUpdate(sql);
			//count down
			wxGetApp().AppDB.CountExpense--;
			wxGetApp().SQLDB().ExecuteUpdate(wxString::Format(_T("update db_counter set ct_expense = %d"),wxGetApp().AppDB.CountExpense));
		}
		dbs.clear();
		dbi = ed_dialog->GetChangedItems(del_mt);
		for (i = 0; i < (int)dbi.size(); i++) {
			wxString sql = wxString::Format(_T("delete from db_items where it_id = %d, it_expense = %d;"),
				dbi.at(i).GetId(),dbi.at(i).GetExpense());
			wxGetApp().SQLDB().ExecuteUpdate(sql);
			//count down
			wxGetApp().AppDB.CountItems--;
			wxGetApp().SQLDB().ExecuteUpdate(wxString::Format(_T("update db_counter set ct_items = %d"),wxGetApp().AppDB.CountItems));
		}
		dbi.clear();
		GenerateExpenseInDetail(true,false,curhandling);
		wxGetApp().SetChangeFlag(true);
	}
}
//---------------------------------------------------------------
// Tool menu - Show account dialog event
//---------------------------------------------------------------
void MyFrame::toolMenu_SetAccount_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	wxString sql = _T("select * from db_account;");
	wxSQLite3ResultSet tbl = wxGetApp().SQLDB().ExecuteQuery(sql);
	ac_dialog->BindData_Account(tbl);
	ac_dialog->ClearControl();
	ac_dialog->CenterOnParent();
	if (ac_dialog->ShowModal() == account_ok) {
		vector <DB_account> dbs;
		int i;
		//---add accounts
		dbs = ac_dialog->GetChangedData(add_mt);
		for (i = 0; i < (int)dbs.size(); i++) {
			int tmpid;
			wxGetApp().AppDB.AddAccount(dbs.at(i));
			//update remainder
			sql = wxString::Format(_T("select ac_id from db_account where ac_name = '%s';"),dbs.at(i).GetName().c_str());
			wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
			while (rset.NextRow()) {
				tmpid = rset.GetInt(0);
				break;
			}
			sql = wxString::Format(_T("insert into db_total values ( '%s', %d, %d, %d, %d );"),
				wxGetApp().AppDB.AppSetting.GetStartDate().Format(DATEFORM).c_str(),tmpid,0,0,dbs.at(i).GetRemain());
			wxGetApp().SQLDB().ExecuteUpdate(sql);
			//count up
			wxGetApp().AppDB.CountAccount++;
			wxGetApp().SQLDB().ExecuteUpdate(wxString::Format(_T("update db_counter set ct_account = %d"),wxGetApp().AppDB.CountAccount));
			wxGetApp().AppDB.CountTotal++;
			wxGetApp().SQLDB().ExecuteUpdate(wxString::Format(_T("update db_counter set ct_total = %d"),wxGetApp().AppDB.CountTotal));
			//---set accounts in items of expense
			int id[2], ix = 0;
			sql = _T("select ex_id from db_expense where ex_account = '1' order by ex_id, ex_io;");
			rset = wxGetApp().SQLDB().ExecuteQuery(sql);
			while (rset.NextRow()) {
				id[ix] = rset.GetInt(0);
				ix++;
			}
			int sid = wxGetApp().AppDB.GetLastIdOfItems(id[0]);
			for (ix = 0; ix < 2; ix++) {
				DB_items db;
				db.SetId(sid);
				db.SetImage(-1);
				db.SetExpense(id[ix]);
				db.SetName(dbs.at(i).GetName());
				wxGetApp().AppDB.AddItems(db);
			}
		}
		dbs.clear();
		//---modify accounts
		dbs = ac_dialog->GetChangedData(mod_mt);
		for (i = 0; i < (int)dbs.size(); i++) {
			wxString sql = wxString::Format(_T("update db_account set ac_name = '%s' where ac_id = %d;"),
				dbs.at(i).GetName().c_str(),dbs.at(i).GetId());
			wxGetApp().SQLDB().ExecuteUpdate(sql);
			//---set accounts in items of expense
			int id[2], ix = 0;
			sql = _T("select ex_id from db_expense where ex_account = '1' order by ex_id, ex_io;");
			wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
			while (rset.NextRow()) {
				id[ix] = rset.GetInt(0);
				ix++;
			}
			for (ix = 0; ix < 2; ix++) {
				sql = StrF(_T("update db_items set it_name = '%s' where it_expense = %d and it_name = '%s';"),
					dbs.at(i).GetName().c_str(),id[ix],dbs.at(i).GetOldName().c_str());
				wxGetApp().SQLDB().ExecuteUpdate(sql);
			}
		}
		dbs.clear();
		//---delete accounts
		dbs = ac_dialog->GetChangedData(del_mt);
		for (i = 0; i < (int)dbs.size(); i++) {
			wxString sql = wxString::Format(_T("delete from db_account where ac_id = %d;"),
				dbs.at(i).GetId());
			wxGetApp().SQLDB().ExecuteUpdate(sql);
			wxGetApp().AppDB.CountAccount--;
			wxGetApp().SQLDB().ExecuteUpdate(wxString::Format(_T("update db_counter set ct_account = %d"),wxGetApp().AppDB.CountAccount));
			//---set accounts in items of expense
			int id[2], ix = 0;
			sql = _T("select ex_id from db_expense where ex_account = '1' order by ex_id, ex_io;");
			wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
			while (rset.NextRow()) {
				id[ix] = rset.GetInt(0);
				ix++;
			}
			for (ix = 0; ix < 2; ix++) {
				sql = StrF(_T("delete from db_items where it_expense = %d and it_name = '%s';"),
					id[ix],dbs.at(i).GetName().c_str());
				wxGetApp().SQLDB().ExecuteUpdate(sql);
			}
		}
		dbs.clear();
		wxGetApp().SetChangeFlag(true);
		UpdateControl();
	}
}
//---------------------------------------------------------------
// Tool menu - Show import and export dialog event
//---------------------------------------------------------------
void MyFrame::toolMenu_Import_clicked(wxCommandEvent &event)
{
	//log_dialog->Show(true);
	im_dialog->Clear();
	im_dialog->CenterOnParent();
	if (im_dialog->ShowModal() == import_close) {

	}
	wxLog::SetActiveTarget(log_dialog);
}
//---------------------------------------------------------------
// Tool menu - Show log dialog event
//---------------------------------------------------------------
void MyFrame::toolMenu_Log_clicked(wxCommandEvent &event)
{
	//wxLog::SetActiveTarget(log_dialog);
	//log_dialog->Show();
	wxSingleChoiceDialog *dlg = new wxSingleChoiceDialog(this,_("Application log list"),APPTITLE,
		wxGetApp().GetLogQueue(),NULL,wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER|wxOK|wxCENTRE);
	dlg->CenterOnParent();
	if (dlg->ShowModal() == wxOK) {

	}
}
//---------------------------------------------------------------
// Tool menu - Delete log event
//---------------------------------------------------------------
void MyFrame::toolMenu_DelLog_clicked(wxCommandEvent &event)
{
	const wxString msg = _("Remove application log. Are you sure?");
	if (wxMessageBox(msg,APPTITLE,wxYES_NO|wxICON_QUESTION,this) == wxYES) {
		wxGetApp().ClearLog();
	}
}
/*void MyFrame::toolMenu_Report_clicked(wxCommandEvent &event)
{
	rep_dialog->Bind_PageData(&pageInfo);
	rep_dialog->Bind_Setup(wxGetApp().AppDB.AppSetting);
	if (rep_dialog->ShowModal()) {

	}
}*/
//---------------------------------------------------------------
// Help menu - Show contents file of manual
//---------------------------------------------------------------
void MyFrame::helpMenu_Contents_clicked(wxCommandEvent &event)
{
	wxFileName fname;
	fname.AssignDir(wxGetApp().GetStdPath().GetResourcesDir());
#ifdef __WXMSW__
	fname.AppendDir(wxGetApp().GetPathElement(P_SHARE));
	fname.AppendDir(wxGetApp().GetPathElement(P_APPNAME));
#endif
	fname.AppendDir(_T("html"));
	fname.SetFullName(_T("index.html"));
	wxLaunchDefaultBrowser(_T("file://")+fname.GetFullPath());

}
//---------------------------------------------------------------
// Help menu - Show about dialog event
//---------------------------------------------------------------
void MyFrame::helpMenu_About_clicked(wxCommandEvent &event)
{
	wxLocale locale;
	locale.Init(wxLANGUAGE_DEFAULT);
	wxAboutDialogInfo info;
	info.SetName(APPTITLE);
	info.SetIcon(wxICON(kakeibomeister));
	info.AddDeveloper(CREATOR);
	info.AddTranslator(CREATOR);
	info.SetVersion(APPVER);
	info.SetDescription(StrF(_T("System language: %s(%s)\n\t%s\nSystem encoding: %s\n\n%s"),
		locale.GetLanguageName(locale.GetSystemLanguage()).c_str(),
		locale.GetCanonicalName().c_str(),
		locale.GetSysName().c_str(),
		locale.GetSystemEncodingName().c_str(),
		_("This program support to manage money and account for you.\nThis program is made with wxWidgets.")
		));
	info.SetCopyright(wxString::Format(_T("(C) 2008 %s < %s >"),CREATOR,EMAIL));
	

	wxAboutBox(info);

}
//---------------------------------------------------------------
// Left pain - Return today event
//---------------------------------------------------------------
void MyFrame::km_ReturnToday_clicked(wxCommandEvent &event)
{
	wxDateTime old;
	//wxDateTime::Month mn;
	//int year;
	old = wxDateTime::Now();
	//wxMessageBox(wxString::Format(_T("%d"),km_CalenYear->GetValue()),_T("abf"),wxOK,this);
	km_CalenYear->SetValue(old.GetYear());
	km_CalenMonth->SetValue((int)old.GetMonth()+1);
	km_Calender->SetDate(old);
	
	if (mainPanel2->GetSelection() == 0) {
		ChangePage(km_Calender->GetDate(),curhandling);
	}else{
		ChangePage(km_Calender->GetDate(),curhandling);
		GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
	}
}
//---------------------------------------------------------------
// Left pain - Add detail data event
//---------------------------------------------------------------
void MyFrame::km_AddDetail_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	if (mainPanel2->GetSelection() != 0) return;
	de_dialog->bindData_InputDate(km_Calender->GetDate());
	de_dialog->SetExpense(in_it);
	de_dialog->SetItems(0);
	de_dialog->SetAccount(curhandling);
	de_dialog->ChangeEnable(true);
	de_dialog->ClearControl();
	de_dialog->CenterOnParent();
	if (de_dialog->ShowModal() == detaile_ok) {
		wxString arr[7];
		int imageid[2];
		DB_day db;
		wxString sql;
		int valueforlog = 0;
		//for listctrl
		arr[0] = de_dialog->GetDataDate().Format(DATEFORM);
		arr[1] = wxGetApp().AppDB.GetExpense(de_dialog->GetDataExpense(),
			de_dialog->GetDataIncome()).GetName();
		imageid[0] = wxGetApp().AppDB.GetExpense(de_dialog->GetDataExpense(),
			de_dialog->GetDataIncome()).GetImage();
		arr[2] = wxGetApp().AppDB.GetItems(de_dialog->GetDataItems(),
			de_dialog->GetDataExpense()).GetName();
		imageid[1] = wxGetApp().AppDB.GetItems(de_dialog->GetDataItems(),
			de_dialog->GetDataExpense()).GetImage();
		int acc = de_dialog->GetDataHandling();
		arr[3] = wxGetApp().AppDB.GetAccount(acc).GetName();
		if (de_dialog->GetDataIncome() == 0) {
			arr[4] = IntToStr(de_dialog->GetDataValue());
			arr[5] = _T(" ");
			db.SetIncome(de_dialog->GetDataValue());
			db.SetExpenditure(0);
			valueforlog += de_dialog->GetDataValue();
		}else{
			arr[4] = _T(" ");
			arr[5] = IntToStr(de_dialog->GetDataValue());
			db.SetIncome(0);
			db.SetExpenditure(de_dialog->GetDataValue());
			valueforlog -= de_dialog->GetDataValue();
		}
		arr[6] = de_dialog->GetDataMemo();
		if (acc == curhandling) {
			InsertRow(km_DayDetail,arr,sizeof(arr),imageid,2);
		}
		//for DB
		db.SetId(wxGetApp().AppDB.GetLastIdOfBudget(de_dialog->GetDataDate(),de_dialog->GetDataIncome(),acc));
		db.SetFlag(add_mt);
		db.SetDate(de_dialog->GetDataDate());
		db.SetIO((InoutType)de_dialog->GetDataIncome());
		db.SetExpense(de_dialog->GetDataExpense());
		db.SetItems(de_dialog->GetDataItems());
		db.SetHandling(acc);
		db.SetMemo(de_dialog->GetDataMemo());
		if ((db.GetExpense() == 3) || (db.GetExpense() == 4)) {
			db.SetExtra(StrF(_T("l%s:"),
				GenerateLinkId(db.GetDate(),db.GetIO(),db.GetHandling(),db.GetId()).c_str()));
		}
		dbbudget.push_back(db);
		
		UpdateLinkedBudget(db);
		UpdateDB();
		if (mainPanel2->GetSelection() == 0) {
			ChangePage(km_Calender->GetDate(),curhandling);
		}else{
			GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
		}
		/*LOG*/wxGetApp().WriteLog(StrF(_("Added the data at %s (%s, %s - %s: %+d)"),
			arr[0].c_str(), arr[3].c_str(),arr[1].c_str(), arr[2].c_str(), valueforlog));
	}
}
//---------------------------------------------------------------
// Left pain - Modify detail data event
//---------------------------------------------------------------
void MyFrame::km_ModDetail_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	if (mainPanel2->GetSelection() != 0) return;
	if (listselect < 0) {
		wxMessageBox(_("Please choose a budget for changing!"),APPTITLE,wxOK|wxICON_EXCLAMATION,this);
		return;
	}
	de_dialog->bindData_InputDate(km_Calender->GetDate());
	de_dialog->bindData_ExistData(dbbudget.at(listselect));
	de_dialog->SetAccount(curhandling);
	dbbudget.at(listselect).SetOldDate(dbbudget.at(listselect).GetDate());
	de_dialog->CenterOnParent();
	if (de_dialog->ShowModal() == detaile_ok) {
		wxString arr[7];
		int imageid[2];
		//DB_day db;
		wxString sql;
		int valueforlog = 0;
		//for listctrl
		arr[0] = de_dialog->GetDataDate().Format(DATEFORM);
		arr[1] = wxGetApp().AppDB.GetExpense(de_dialog->GetDataExpense(),
			de_dialog->GetDataIncome()).GetName();
		imageid[0] = wxGetApp().AppDB.GetExpense(de_dialog->GetDataExpense(),
			de_dialog->GetDataIncome()).GetImage();
		arr[2] = wxGetApp().AppDB.GetItems(de_dialog->GetDataItems(),
			de_dialog->GetDataExpense()).GetName();
		imageid[1] = wxGetApp().AppDB.GetItems(de_dialog->GetDataItems(),
			de_dialog->GetDataExpense()).GetImage();
		int acc = de_dialog->GetDataHandling();
		arr[3] = wxGetApp().AppDB.GetAccount(acc).GetName();
		if (de_dialog->GetDataIncome() == 0) {
			arr[4] = IntToStr(de_dialog->GetDataValue());
			arr[5] = _T(" ");
			dbbudget.at(listselect).SetIncome(de_dialog->GetDataValue());
			dbbudget.at(listselect).SetExpenditure(0);
			valueforlog += de_dialog->GetDataValue();
		}else{
			arr[4] = _T(" ");
			arr[5] = IntToStr(de_dialog->GetDataValue());
			dbbudget.at(listselect).SetIncome(0);
			dbbudget.at(listselect).SetExpenditure(de_dialog->GetDataValue());
			valueforlog -= de_dialog->GetDataValue();
		}
		arr[6] = de_dialog->GetDataMemo();
		ChangeRow(km_DayDetail,listselect,arr,sizeof(arr),imageid,2);
		//for DB
		sql = _T("select %s(bg_id) from db_budgets where bg_date = '%s'");
		int cnt = wxGetApp().SQLDB().ExecuteScalar(
			StrF(sql,_T("count"),de_dialog->GetDataDate().Format(DATEFORM).c_str()));
		dbbudget.at(listselect).SetFlag(mod_mt);
		dbbudget.at(listselect).SetDate(de_dialog->GetDataDate());
		dbbudget.at(listselect).SetIO((InoutType)de_dialog->GetDataIncome());
		dbbudget.at(listselect).SetExpense(de_dialog->GetDataExpense());
		dbbudget.at(listselect).SetItems(de_dialog->GetDataItems());
		dbbudget.at(listselect).SetHandling(acc);
		dbbudget.at(listselect).SetMemo(de_dialog->GetDataMemo());
		
		UpdateLinkedBudget(dbbudget.at(listselect));
		UpdateDB();
		if (mainPanel2->GetSelection() == 0) {
			ChangePage(km_Calender->GetDate(),curhandling);
		}else{
			GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
		}
	/*LOG*/wxGetApp().WriteLog(StrF(_("Changed the data at %s (%s, %s - %s: %+d)"),
		arr[0].c_str(), arr[3].c_str(),arr[1].c_str(), arr[2].c_str(), valueforlog));
	}

}
//---------------------------------------------------------------
// Left pain - Remove detail data event
//---------------------------------------------------------------
void MyFrame::km_DelDetail_clicked(wxCommandEvent &event)
{
	if (!wxGetApp().SQLDB().IsOpen()) return;
	if (listselect < 0) {
		wxMessageBox(_("Please choose a budget for removing!"),APPTITLE,wxOK|wxICON_EXCLAMATION,this);
		return;
	}
	if (wxMessageBox(_("Do you realy remove this budget?"),APPTITLE,wxYES_NO|wxICON_QUESTION,this)
		== wxNO) {
		return;
	}
	//for DB
	dbbudget.at(listselect).SetFlag(del_mt);

	UpdateLinkedBudget(dbbudget.at(listselect));
	UpdateDB();
	if (mainPanel2->GetSelection() == 0) {
		ChangePage(km_Calender->GetDate(),curhandling);
	}else{
		GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
	}
	/*LOG*/wxGetApp().WriteLog(StrF(_("Removed the data at %s."),km_Calender->GetDate().Format(DATEFORM).c_str()));
}
//---------------------------------------------------------------
// Left pain - Change Year/Month SpinCtrl event
//---------------------------------------------------------------
void MyFrame::km_CalenYM_spined(wxSpinEvent &event)
{
	wxDateTime old;
	wxDateTime::Month mn;
	int year;
	year = km_CalenYear->GetValue();
	mn = (wxDateTime::Month)(km_CalenMonth->GetValue()-1);
	old = km_Calender->GetDate();
	km_Calender->SetDate(wxDateTime(old.GetDay(),mn,year));
	
	if (mainPanel2->GetSelection() == 0) {
		ChangePage(km_Calender->GetDate(),curhandling);
	}else{
		ChangePage(km_Calender->GetDate(),curhandling);
		GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
	}
}
//---------------------------------------------------------------
// Left pain - Change Calendar date event
//---------------------------------------------------------------
void MyFrame::km_Calender_changed(wxCalendarEvent &event)
{
	km_CalenYear->SetValue(event.GetDate().GetYear());
	km_CalenMonth->SetValue((int)event.GetDate().GetMonth() + 1);
	if (mainPanel2->GetSelection() == 0) {
		ChangePage(km_Calender->GetDate(),curhandling);
	}else{
		ChangePage(km_Calender->GetDate(),curhandling);
		GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
	}
}
//---------------------------------------------------------------
// Right pain - select Day Detail event
//---------------------------------------------------------------
void MyFrame::km_DayDetail_selected(wxListEvent &event)
{
	listselect = event.GetIndex();
}
//---------------------------------------------------------------
// Right pain - unselect Day Detail event
//---------------------------------------------------------------
void MyFrame::km_DayDetail_deselected(wxListEvent &event)
{
	listselect = -1;
}
//---------------------------------------------------------------
// Right pain - active Day Detail event
//---------------------------------------------------------------
void MyFrame::km_DayDetail_activated(wxListEvent &event)
{
	km_ModDetail_clicked((wxCommandEvent&)event);
}
//---------------------------------------------------------------
// Right pain - Change tab of mainPanel2 event
//---------------------------------------------------------------
void MyFrame::mainPanel2_changed(wxNotebookEvent &event)
{
	if (event.GetSelection() > 0) {
		mainPanel2->Freeze();
		GenerateExpenseInDetail(false,true,curhandling,event.GetSelection());
		mainPanel2->Thaw();
		switch (event.GetSelection()) {
		case 0:
			km_MenuBar->Check(kakeibo_viewday,true);
			break;
		case 1:
			km_MenuBar->Check(kakeibo_viewweek,true);
			break;
		case 2:
			km_MenuBar->Check(kakeibo_viewmonth,true);
			break;
		case 3:
			km_MenuBar->Check(kakeibo_viewsearch,true);
			break;
		case 4:
			km_MenuBar->Check(kakeibo_viewreport,true);
			break;
		}
	}
}
//---------------------------------------------------------------
// Tool bar - select handling/account event
//---------------------------------------------------------------
void MyFrame::km_tool_Handling_selected(wxCommandEvent &event)
{
	curhandling = dbaccountId.at(km_tool_Handling->GetSelection());
	/*LOG*/wxGetApp().WriteLog(StrF(_("Handling is changing %s."),wxGetApp().AppDB.GetAccount(curhandling).GetName().c_str()));
	if (mainPanel2->GetSelection() == 0) {
		ChangePage(km_Calender->GetDate(),curhandling);
	}else{
		ChangePage(km_Calender->GetDate(),curhandling);
		GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
	}
}
//---------------------------------------------------------------
// MyFrame - window close event
//---------------------------------------------------------------
void MyFrame::MyFrame_close(wxCloseEvent &event)
{
	if (Close_File() == 0) {
		wxGetApp().SaveIni();
		this->Destroy();
	}else{
		if (event.CanVeto()) {
			event.Veto();
		}else{
			wxGetApp().SaveIni();
			this->Destroy();
		}
	}
}
//---------------------------------------------------------------
// Left pain - double click stack period item event
//---------------------------------------------------------------
void MyFrame::km_StackPeriod_dblclicked(wxCommandEvent &event)
{
	int i = event.GetSelection();
	//---no stack
	if (stock_dbperiod.size() == 0) return;
	//---when stack have operation to input amount or memo
	if (stock_dbperiod.at(i).GetInputValue() || stock_dbperiod.at(i).GetInputMemo()) {
		de_dialog->ChangeEnable(-2,false);
		de_dialog->SetAccount(stock_dbperiod.at(i).GetBudget().GetHandling());
		de_dialog->bindData_InputDate(stock_dbperiod.at(i).GetDate());
		de_dialog->bindData_ExistData(stock_dbperiod.at(i).GetBudget());
		de_dialog->CenterOnParent();
		if (de_dialog->ShowModal() == detaile_ok) {
			DB_day db;
			db = stock_dbperiod.at(i).GetBudget();
			db.SetFlag(add_mt);
			if (stock_dbperiod.at(i).GetInputValue()) {
				if (de_dialog->GetDataIncome() == 0) {
					db.SetIncome(de_dialog->GetDataValue());
					db.SetExpenditure(0);
				}else{
					db.SetIncome(0);
					db.SetExpenditure(de_dialog->GetDataValue());
				}
			}
			if (stock_dbperiod.at(i).GetInputMemo()) {
				db.SetMemo(de_dialog->GetDataMemo());
			}
			dbbudget.push_back(db);
			UpdateLinkedBudget(db);
			UpdateDB();
			stock_dbperiod.erase(stock_dbperiod.begin()+i);
			//---Update listbox and label
			km_StackPeriod->Delete(i);
			if (stock_dbperiod.size() == 0) {
				//km_InfoPeriod->SetLabel(wxEmptyString);
				km_TurnStackPeriod->SetLabel(_("Awaiting"));
			}else{
				//km_InfoPeriod->SetLabel(StrF(_("%d awaiting!"),stock_dbperiod.size()));
				km_TurnStackPeriod->SetLabel(StrF(_T("%s (%d)"),_("Awaiting"),stock_dbperiod.size()));
			}
		}
	}
}
//---------------------------------------------------------------
// Right pain - Change IO in search tab event
//---------------------------------------------------------------
void MyFrame::km_SerIO_changed(wxCommandEvent &event)
{
	SetExpense((InoutType)event.GetSelection());
	km_SerExpense->SetSelection(event.GetSelection());
	SetItems(1);
	km_SerItems->SetSelection(0);
}
//---------------------------------------------------------------
// Right pain - Change Expense in search tab event
//---------------------------------------------------------------
void MyFrame::km_SerUseExpense_changed(wxCommandEvent &event)
{
	SetItems(dbexpenseId.at(event.GetSelection()));
	km_SerItems->SetSelection(0);
}
//---------------------------------------------------------------
// Right pain - Click Add in search tab event
//---------------------------------------------------------------
void MyFrame::km_SerAdd_clicked(wxCommandEvent &event)
{
	wxString line, str;
	line.Clear();
	str.Clear();
	str = StrF(_T(" %s "),km_SerAndCond->GetStringSelection().c_str());
	if (km_SerCondList->GetCount() >= 1) {
		line = StrF(_T(" %s "),km_SerAndCond->GetStringSelection().c_str());
	}
	//---Use a date for condition
	if (event.GetId() == kakeibo_seraddio) {
		line += StrF(_T("%s = %s"),_("Income and Expenditure division"),
			km_SerIO->GetStringSelection().c_str());
		str += StrF(_T("bg_io = %d"),km_SerIO->GetSelection());
	}else if (event.GetId() == kakeibo_seradddate) {
		line += StrF(_T("%s %s %s"),_("Date"),
			km_SerDateCond->GetStringSelection().c_str(),
			km_SerDate->GetValue().Format(DATEFORM).c_str());
		str += StrF(_T("bg_date %s '%s'"),
			km_SerDateCond->GetStringSelection().c_str(),
			km_SerDate->GetValue().Format(DATEFORM).c_str());
	//---Use a handling for condition
	}else if (event.GetId() == kakeibo_seraddaccount) {
		line += StrF(_T("%s = %s"),_("Handling"),
			km_SerHandling->GetStringSelection().c_str());
		str += StrF(_T("bg_handle = %d"),dbaccountId.at(km_SerHandling->GetSelection()));
	//---Use a Expense for condition
	}else if (event.GetId() == kakeibo_seraddexpense) {
		line += StrF(_T("%s = %s"),_("Expense"),
			km_SerExpense->GetStringSelection().c_str());
		str += StrF(_T("bg_expense = %d"),dbexpenseId.at(km_SerExpense->GetSelection()));
		//---Use items of expense for condition
		if (km_SerUserItems->GetValue()) {
			line += StrF(_T(" and %s = %s"),_("Items"),
				km_SerItems->GetStringSelection().c_str());
			str += StrF(_T(" and bg_items = %d"),dbitemsId.at(km_SerItems->GetSelection()));
		}
	//---Use an income and expenditure for condition
	}else if (event.GetId() == kakeibo_seraddamount) {
		line += StrF(_T("%s %s %d"),(km_SerIO->GetSelection() == 0 ? _("Income") : _("Expenditure")),
			km_SerIncomeCond->GetStringSelection().c_str(),
			km_SerIncome->GetValue());
		str += StrF(_T("%s %s %d"),(km_SerIO->GetSelection() == 0 ? _T("bg_income") : _T("bg_expenditure")),
			km_SerIncomeCond->GetStringSelection().c_str(),
			km_SerIncome->GetValue());
	}
	km_SerCondList->Append(line);
	searchstrs.Add(str);
}
//---------------------------------------------------------------
// Right pain - Click Del in search tab event
//---------------------------------------------------------------
void MyFrame::km_SerDel_clicked(wxCommandEvent &event)
{
	if (km_SerCondList->GetSelection() == wxNOT_FOUND) return;
	if ((int)searchstrs.GetCount() <= km_SerCondList->GetSelection()) return;
	searchstrs.RemoveAt(km_SerCondList->GetSelection());
	km_SerCondList->Delete(km_SerCondList->GetSelection());
}
//---------------------------------------------------------------
// Right pain - Click Execute in search tab event
//---------------------------------------------------------------
void MyFrame::km_SerExecute_clicked(wxCommandEvent &event)
{
	wxString sql = _T("select * from db_budgets where 0 = 0 ");
	for (int i = 0; i < (int)searchstrs.GetCount(); i++) {
		sql.Append(searchstrs.Item(i).c_str());
	}
	//Msgbox(sql,this);
	wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
	km_SearchDetail->Freeze();
	km_SearchDetail->DeleteAllItems();
	dbsearch.clear();
	while (rset.NextRow()) {
		DB_day db;
		db.SetDate(rset.GetDate(0));
		db.SetId(rset.GetInt(1));
		db.SetIO((InoutType)rset.GetInt(2));
		db.SetHandling(rset.GetInt(3));
		db.SetExpense(rset.GetInt(4));
		db.SetItems(rset.GetInt(5));
		db.SetIncome(rset.GetInt(6));
		db.SetExpenditure(rset.GetInt(7));
		db.SetMemo(rset.GetString(8));
		dbsearch.push_back(db);
		wxString arr[7];
		int imageid[2];
		arr[0] = rset.GetString(0);
		arr[1] = wxGetApp().AppDB.GetExpense(rset.GetInt(4),(InoutType)rset.GetInt(2)).GetName();
		imageid[0] = wxGetApp().AppDB.GetExpense(rset.GetInt(4),(InoutType)rset.GetInt(2)).GetImage();
		arr[2] = wxGetApp().AppDB.GetItems(rset.GetInt(5),rset.GetInt(4)).GetName();
		imageid[1] = wxGetApp().AppDB.GetItems(rset.GetInt(5),rset.GetInt(4)).GetImage();
		arr[3] = wxGetApp().AppDB.GetAccount(rset.GetInt(3)).GetName();
		arr[4] = rset.GetString(6);
		arr[5] = rset.GetString(7);
		arr[6] = rset.GetString(8);
		InsertRow(km_SearchDetail,arr,sizeof(arr),imageid,2);
	}
	km_SearchDetail->Thaw();
	SetStatusText(_("Search finished."),0);
	searchSQL = sql;
}
//---------------------------------------------------------------
// Right pain - Click Clear in search tab event
//---------------------------------------------------------------
void MyFrame::km_SerClear_clicked(wxCommandEvent &event)
{
	km_SearchDetail->DeleteAllItems();
	km_SerCondList->Clear();
	searchstrs.Clear();
}
//---------------------------------------------------------------
// Right pain - Click km_SearchDetail Column in search tab event
//---------------------------------------------------------------
void MyFrame::km_SearchDetail_colclicked(wxListEvent &event)
{
	wxString sql;
	static bool is_asc = true;
	switch (event.GetColumn()) {
	case 0://date
		sql = searchSQL + _T(" order by bg_date");
		break;
	case 1://expense
		sql = searchSQL + _T(" order by bg_expense");
		break;
	case 2://items
		sql = searchSQL + _T(" order by bg_items");
		break;
	case 3://handling
		sql = searchSQL + _T(" order by bg_handling");
		break;
	case 4://income
		sql = searchSQL + _T(" order by bg_income");
		break;
	case 5://expenditure
		sql = searchSQL + _T(" order by bg_expenditure");
		break;
	case 6://memo
		sql = searchSQL + _T(" order by bg_memo");
		break;
	}
	if (is_asc) {
		sql += _T(" asc");
	}else{
		sql += _T(" desc");
	}
	is_asc = !is_asc;
	//---re-execute and sort SearchDetail list item
	wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
	km_SearchDetail->Freeze();
	km_SearchDetail->DeleteAllItems();
	while (rset.NextRow()) {
		wxString arr[7];
		int imageid[2];
		arr[0] = rset.GetString(0);
		arr[1] = wxGetApp().AppDB.GetExpense(rset.GetInt(4),(InoutType)rset.GetInt(2)).GetName();
		imageid[0] = wxGetApp().AppDB.GetExpense(rset.GetInt(4),(InoutType)rset.GetInt(2)).GetImage();
		arr[2] = wxGetApp().AppDB.GetItems(rset.GetInt(5),rset.GetInt(4)).GetName();
		imageid[1] = wxGetApp().AppDB.GetItems(rset.GetInt(5),rset.GetInt(4)).GetImage();
		arr[3] = wxGetApp().AppDB.GetAccount(rset.GetInt(3)).GetName();
		arr[4] = rset.GetString(6);
		arr[5] = rset.GetString(7);
		arr[6] = rset.GetString(8);
		InsertRow(km_SearchDetail,arr,sizeof(arr),imageid,2);
	}
	km_SearchDetail->Thaw();
}
//---------------------------------------------------------------
// Right pain - botu botu botu botu botu
//---------------------------------------------------------------
void MyFrame::km_ChartOn_clicked(wxCommandEvent &event)
{
	wxString sql;
	wxSQLite3ResultSet rset;
	wxArrayInt crt;
	wxDateTime tmpdate, tmpdate2;
	wxArrayString arr1, arr2;
	const int periodcash = 1000;
	switch (km_ChartSource->GetSelection()) {
	case 0:
		sql = StrF(_T("select bg_income, bg_expenditure, bg_memo from db_budgets where bg_date = '%s' and bg_handle = %d order by bg_io, bg_id;"),
			km_Calender->GetDate().Format(DATEFORM).c_str(),dbaccountId.at(km_tool_Handling->GetSelection()));
		rset = wxGetApp().SQLDB().ExecuteQuery(sql);
		while (rset.NextRow()) {
			crt.Add(rset.GetInt(0));
			crt.Add(rset.GetInt(1));
			arr2.Add(rset.GetString(2));
			arr2.Add(wxEmptyString);
		}
		km_ChartMain->SetChartTitle(StrF(_T("(%s)"),km_Calender->GetDate().Format(DATEFORM).c_str()),15,km_ChartMain->GetSize().GetHeight()-20);
		break;
	case 1:
		tmpdate.ParseDate(km_WeekDetail->GetColLabelValue(4));
		tmpdate2 = tmpdate;
		tmpdate2.Add(wxDateSpan(0,0,0,7));
		sql = StrF(WXSQL_FOR_EXPENSEONLY,
			tmpdate.Format(DATEFORM).c_str(),tmpdate2.Format(DATEFORM).c_str(),dbaccountId.at(km_tool_Handling->GetSelection()));
		rset = wxGetApp().SQLDB().ExecuteQuery(sql);
		while (rset.NextRow()) {
			crt.Add(rset.GetInt(1));
			crt.Add(rset.GetInt(2));
			if (rset.GetInt(1) > 0) {
				arr2.Add(rset.GetString(0));
				arr2.Add(wxEmptyString);
			}else if (rset.GetInt(2) > 0) {
				arr2.Add(wxEmptyString);
				arr2.Add(rset.GetString(0));
			}else{
				arr2.Add(rset.GetString(0));
				arr2.Add(wxEmptyString);
			}
		}
		km_ChartMain->SetChartTitle(StrF(_T("(%s)"),tmpdate.Format(DATEFORM).c_str()),15,km_ChartMain->GetSize().GetHeight()-20);
		break;
	}
	km_ChartMain->SetRange(0,(int)crt.GetCount());
	km_ChartMain->SetValueRange(0,15000);
	km_ChartMain->border = true;
	km_ChartMain->lineborder = true;
	km_ChartMain->SetColor(wxColour(0,0,255));
	km_ChartMain->SetHelperLine((int)crt.GetCount(),periodcash);
	km_ChartMain->SetHelperStyle(wxPen(wxColour(255,125,255),1,wxSOLID));
	km_ChartMain->SetHelperValue(true,true);
	for (int i = periodcash; i < 15001; i+=periodcash) {
		arr1.Add(IntToStr(i));
	}
	km_ChartMain->SetValueName(arr2,arr1);
	km_ChartMain->DrawChart(crt);
	km_ChartMain->Refresh();
}
//---------------------------------------------------------------
// Left pain - Jump to past/future data event
//---------------------------------------------------------------
void MyFrame::km_JumpBtn_clicked(wxCommandEvent &event)
{
	wxDateTime date;
	int cnt = 0;
	wxString opr = (event.GetId() == kakeibo_jumppast ? _T("<") : _T(">"));
	wxString ord = (event.GetId() == kakeibo_jumppast ? _T("desc") : _T("asc"));
	wxString sql = StrF(_T("select bg_date from db_budgets where bg_date %s '%s' and bg_handle = %d order by bg_date %s limit 1"),
		opr.c_str(),km_Calender->GetDate().Format(DATEFORM).c_str(), 
		curhandling, ord.c_str());
	wxSQLite3ResultSet rset = wxGetApp().SQLDB().ExecuteQuery(sql);
	while (rset.NextRow()) {
		//cnt = rset.GetInt(0);
		date = rset.GetDate(0);
		cnt++;
		break;
	}
	if (cnt > 0) {
		km_Calender->SetDate(date);
		km_CalenYear->SetValue(date.GetYear());
		km_CalenMonth->SetValue((int)date.GetMonth() + 1);
		if (mainPanel2->GetSelection() == 0) {
			ChangePage(date,curhandling);
		}else{
			ChangePage(date,curhandling);
			GenerateExpenseInDetail(false,true,curhandling,mainPanel2->GetSelection());
		}

	}else{
		wxString mes;
		if (event.GetId() == kakeibo_jumppast) {
			mes = _("There are not the data which are past than now!");
		}else{
			mes = _("There are not the data which are future than now!");
		}
		wxMessageBox(mes,APPTITLE,wxOK|wxICON_EXCLAMATION,this);
	}
}
//---------------------------------------------------------------
// Left pain - Click Clear finished transaction
//---------------------------------------------------------------
void MyFrame::km_ClearPeriod_clicked(wxCommandEvent &event)
{
	wxString mes = _("Do you really clear finished periodical list?");
	if (wxYES == wxMessageBox(mes,APPTITLE,wxYES_NO|wxICON_QUESTION,this)) {
		km_FinishPeriod->Clear();
		km_TurnFinishPeriod->SetLabel(_("Processed"));
	}
}
//---------------------------------------------------------------
// Left pain - Click Turn*period Button
//---------------------------------------------------------------
void MyFrame::km_Turn_Period_clicked(wxCommandEvent &event)
{
	if (event.GetId() == kakeibo_turnstackperiod) {
		show_stackperiod = !show_stackperiod;
		mstsizer->Show(km_InfoPeriod,show_stackperiod);
		mstsizer->Show(km_StackPeriod,show_stackperiod);
		mstsizer->Layout();
	}else if (event.GetId() == kakeibo_turnfinishperiod) {
		show_finishperiod = !show_finishperiod;
		mstsizer->Show(km_ClearPeriod,show_finishperiod);
		mstsizer->Show(km_FinishPeriod,show_finishperiod);
		mstsizer->Layout();
	}
}
//---------------------------------------------------------------
// DDFile - Drop files in the area event
//---------------------------------------------------------------
bool DDFile::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString &filenames)
{
	size_t cnt = filenames.GetCount();
	if (cnt >= 1) {
		wxFileName name(filenames.Item(0));
		if (name.GetExt().Lower().Find(_T("kak")) == wxNOT_FOUND) return false;
		((MyFrame*)owner)->Open_File(filenames.Item(0));
		return true;
	}
	return false;
}
